sandbox: refactor string-based option-unchanged tests to use a macro
[tor.git] / src / common / container.c
blobb937d544fc0fb25315f3265bf337f5722d514954
1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2013, 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 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_malloc(sizeof(void *) * sl->capacity);
38 return sl;
41 /** Deallocate a smartlist. Does not release storage associated with the
42 * list's elements.
44 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 sl->num_used = 0;
61 /** Make sure that <b>sl</b> can hold at least <b>size</b> entries. */
62 static INLINE void
63 smartlist_ensure_capacity(smartlist_t *sl, int size)
65 #if SIZEOF_SIZE_T > SIZEOF_INT
66 #define MAX_CAPACITY (INT_MAX)
67 #else
68 #define MAX_CAPACITY (int)((SIZE_MAX / (sizeof(void*))))
69 #endif
70 if (size > sl->capacity) {
71 int higher = sl->capacity;
72 if (PREDICT_UNLIKELY(size > MAX_CAPACITY/2)) {
73 tor_assert(size <= MAX_CAPACITY);
74 higher = MAX_CAPACITY;
75 } else {
76 while (size > higher)
77 higher *= 2;
79 sl->capacity = higher;
80 sl->list = tor_realloc(sl->list, sizeof(void*)*((size_t)sl->capacity));
84 /** Append element to the end of the list. */
85 void
86 smartlist_add(smartlist_t *sl, void *element)
88 smartlist_ensure_capacity(sl, sl->num_used+1);
89 sl->list[sl->num_used++] = element;
92 /** Append each element from S2 to the end of S1. */
93 void
94 smartlist_add_all(smartlist_t *s1, const smartlist_t *s2)
96 int new_size = s1->num_used + s2->num_used;
97 tor_assert(new_size >= s1->num_used); /* check for overflow. */
98 smartlist_ensure_capacity(s1, new_size);
99 memcpy(s1->list + s1->num_used, s2->list, s2->num_used*sizeof(void*));
100 s1->num_used = new_size;
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.
107 void
108 smartlist_remove(smartlist_t *sl, const void *element)
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 */
120 /** If <b>sl</b> is nonempty, remove and return the final element. Otherwise,
121 * return NULL. */
122 void *
123 smartlist_pop_last(smartlist_t *sl)
125 tor_assert(sl);
126 if (sl->num_used)
127 return sl->list[--sl->num_used];
128 else
129 return NULL;
132 /** Reverse the order of the items in <b>sl</b>. */
133 void
134 smartlist_reverse(smartlist_t *sl)
136 int i, j;
137 void *tmp;
138 tor_assert(sl);
139 for (i = 0, j = sl->num_used-1; i < j; ++i, --j) {
140 tmp = sl->list[i];
141 sl->list[i] = sl->list[j];
142 sl->list[j] = tmp;
146 /** If there are any strings in sl equal to element, remove and free them.
147 * Does not preserve order. */
148 void
149 smartlist_string_remove(smartlist_t *sl, const char *element)
151 int i;
152 tor_assert(sl);
153 tor_assert(element);
154 for (i = 0; i < sl->num_used; ++i) {
155 if (!strcmp(element, sl->list[i])) {
156 tor_free(sl->list[i]);
157 sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
158 i--; /* so we process the new i'th element */
163 /** Return true iff some element E of sl has E==element.
166 smartlist_contains(const smartlist_t *sl, const void *element)
168 int i;
169 for (i=0; i < sl->num_used; i++)
170 if (sl->list[i] == element)
171 return 1;
172 return 0;
175 /** Return true iff <b>sl</b> has some element E such that
176 * !strcmp(E,<b>element</b>)
179 smartlist_contains_string(const smartlist_t *sl, const char *element)
181 int i;
182 if (!sl) return 0;
183 for (i=0; i < sl->num_used; i++)
184 if (strcmp((const char*)sl->list[i],element)==0)
185 return 1;
186 return 0;
189 /** If <b>element</b> is equal to an element of <b>sl</b>, return that
190 * element's index. Otherwise, return -1. */
192 smartlist_string_pos(const smartlist_t *sl, const char *element)
194 int i;
195 if (!sl) return -1;
196 for (i=0; i < sl->num_used; i++)
197 if (strcmp((const char*)sl->list[i],element)==0)
198 return i;
199 return -1;
202 /** Return true iff <b>sl</b> has some element E such that
203 * !strcasecmp(E,<b>element</b>)
206 smartlist_contains_string_case(const smartlist_t *sl, const char *element)
208 int i;
209 if (!sl) return 0;
210 for (i=0; i < sl->num_used; i++)
211 if (strcasecmp((const char*)sl->list[i],element)==0)
212 return 1;
213 return 0;
216 /** Return true iff <b>sl</b> has some element E such that E is equal
217 * to the decimal encoding of <b>num</b>.
220 smartlist_contains_int_as_string(const smartlist_t *sl, int num)
222 char buf[32]; /* long enough for 64-bit int, and then some. */
223 tor_snprintf(buf,sizeof(buf),"%d", num);
224 return smartlist_contains_string(sl, buf);
227 /** Return true iff the two lists contain the same strings in the same
228 * order, or if they are both NULL. */
230 smartlist_strings_eq(const smartlist_t *sl1, const smartlist_t *sl2)
232 if (sl1 == NULL)
233 return sl2 == NULL;
234 if (sl2 == NULL)
235 return 0;
236 if (smartlist_len(sl1) != smartlist_len(sl2))
237 return 0;
238 SMARTLIST_FOREACH(sl1, const char *, cp1, {
239 const char *cp2 = smartlist_get(sl2, cp1_sl_idx);
240 if (strcmp(cp1, cp2))
241 return 0;
243 return 1;
246 /** Return true iff the two lists contain the same int pointer values in
247 * the same order, or if they are both NULL. */
249 smartlist_ints_eq(const smartlist_t *sl1, const smartlist_t *sl2)
251 if (sl1 == NULL)
252 return sl2 == NULL;
253 if (sl2 == NULL)
254 return 0;
255 if (smartlist_len(sl1) != smartlist_len(sl2))
256 return 0;
257 SMARTLIST_FOREACH(sl1, int *, cp1, {
258 int *cp2 = smartlist_get(sl2, cp1_sl_idx);
259 if (*cp1 != *cp2)
260 return 0;
262 return 1;
265 /** Return true iff <b>sl</b> has some element E such that
266 * tor_memeq(E,<b>element</b>,DIGEST_LEN)
269 smartlist_contains_digest(const smartlist_t *sl, const char *element)
271 int i;
272 if (!sl) return 0;
273 for (i=0; i < sl->num_used; i++)
274 if (tor_memeq((const char*)sl->list[i],element,DIGEST_LEN))
275 return 1;
276 return 0;
279 /** Return true iff some element E of sl2 has smartlist_contains(sl1,E).
282 smartlist_overlap(const smartlist_t *sl1, const smartlist_t *sl2)
284 int i;
285 for (i=0; i < sl2->num_used; i++)
286 if (smartlist_contains(sl1, sl2->list[i]))
287 return 1;
288 return 0;
291 /** Remove every element E of sl1 such that !smartlist_contains(sl2,E).
292 * Does not preserve the order of sl1.
294 void
295 smartlist_intersect(smartlist_t *sl1, const smartlist_t *sl2)
297 int i;
298 for (i=0; i < sl1->num_used; i++)
299 if (!smartlist_contains(sl2, sl1->list[i])) {
300 sl1->list[i] = sl1->list[--sl1->num_used]; /* swap with the end */
301 i--; /* so we process the new i'th element */
305 /** Remove every element E of sl1 such that smartlist_contains(sl2,E).
306 * Does not preserve the order of sl1.
308 void
309 smartlist_subtract(smartlist_t *sl1, const smartlist_t *sl2)
311 int i;
312 for (i=0; i < sl2->num_used; i++)
313 smartlist_remove(sl1, sl2->list[i]);
316 /** Remove the <b>idx</b>th element of sl; if idx is not the last
317 * element, swap the last element of sl into the <b>idx</b>th space.
319 void
320 smartlist_del(smartlist_t *sl, int idx)
322 tor_assert(sl);
323 tor_assert(idx>=0);
324 tor_assert(idx < sl->num_used);
325 sl->list[idx] = sl->list[--sl->num_used];
328 /** Remove the <b>idx</b>th element of sl; if idx is not the last element,
329 * moving all subsequent elements back one space. Return the old value
330 * of the <b>idx</b>th element.
332 void
333 smartlist_del_keeporder(smartlist_t *sl, int idx)
335 tor_assert(sl);
336 tor_assert(idx>=0);
337 tor_assert(idx < sl->num_used);
338 --sl->num_used;
339 if (idx < sl->num_used)
340 memmove(sl->list+idx, sl->list+idx+1, sizeof(void*)*(sl->num_used-idx));
343 /** Insert the value <b>val</b> as the new <b>idx</b>th element of
344 * <b>sl</b>, moving all items previously at <b>idx</b> or later
345 * forward one space.
347 void
348 smartlist_insert(smartlist_t *sl, int idx, void *val)
350 tor_assert(sl);
351 tor_assert(idx>=0);
352 tor_assert(idx <= sl->num_used);
353 if (idx == sl->num_used) {
354 smartlist_add(sl, val);
355 } else {
356 smartlist_ensure_capacity(sl, sl->num_used+1);
357 /* Move other elements away */
358 if (idx < sl->num_used)
359 memmove(sl->list + idx + 1, sl->list + idx,
360 sizeof(void*)*(sl->num_used-idx));
361 sl->num_used++;
362 sl->list[idx] = val;
367 * Split a string <b>str</b> along all occurrences of <b>sep</b>,
368 * appending the (newly allocated) split strings, in order, to
369 * <b>sl</b>. Return the number of strings added to <b>sl</b>.
371 * If <b>flags</b>&amp;SPLIT_SKIP_SPACE is true, remove initial and
372 * trailing space from each entry.
373 * If <b>flags</b>&amp;SPLIT_IGNORE_BLANK is true, remove any entries
374 * of length 0.
375 * If <b>flags</b>&amp;SPLIT_STRIP_SPACE is true, strip spaces from each
376 * split string.
378 * If <b>max</b>\>0, divide the string into no more than <b>max</b> pieces. If
379 * <b>sep</b> is NULL, split on any sequence of horizontal space.
382 smartlist_split_string(smartlist_t *sl, const char *str, const char *sep,
383 int flags, int max)
385 const char *cp, *end, *next;
386 int n = 0;
388 tor_assert(sl);
389 tor_assert(str);
391 cp = str;
392 while (1) {
393 if (flags&SPLIT_SKIP_SPACE) {
394 while (TOR_ISSPACE(*cp)) ++cp;
397 if (max>0 && n == max-1) {
398 end = strchr(cp,'\0');
399 } else if (sep) {
400 end = strstr(cp,sep);
401 if (!end)
402 end = strchr(cp,'\0');
403 } else {
404 for (end = cp; *end && *end != '\t' && *end != ' '; ++end)
408 tor_assert(end);
410 if (!*end) {
411 next = NULL;
412 } else if (sep) {
413 next = end+strlen(sep);
414 } else {
415 next = end+1;
416 while (*next == '\t' || *next == ' ')
417 ++next;
420 if (flags&SPLIT_SKIP_SPACE) {
421 while (end > cp && TOR_ISSPACE(*(end-1)))
422 --end;
424 if (end != cp || !(flags&SPLIT_IGNORE_BLANK)) {
425 char *string = tor_strndup(cp, end-cp);
426 if (flags&SPLIT_STRIP_SPACE)
427 tor_strstrip(string, " ");
428 smartlist_add(sl, string);
429 ++n;
431 if (!next)
432 break;
433 cp = next;
436 return n;
439 /** Allocate and return a new string containing the concatenation of
440 * the elements of <b>sl</b>, in order, separated by <b>join</b>. If
441 * <b>terminate</b> is true, also terminate the string with <b>join</b>.
442 * If <b>len_out</b> is not NULL, set <b>len_out</b> to the length of
443 * the returned string. Requires that every element of <b>sl</b> is
444 * NUL-terminated string.
446 char *
447 smartlist_join_strings(smartlist_t *sl, const char *join,
448 int terminate, size_t *len_out)
450 return smartlist_join_strings2(sl,join,strlen(join),terminate,len_out);
453 /** As smartlist_join_strings, but instead of separating/terminated with a
454 * NUL-terminated string <b>join</b>, uses the <b>join_len</b>-byte sequence
455 * at <b>join</b>. (Useful for generating a sequence of NUL-terminated
456 * strings.)
458 char *
459 smartlist_join_strings2(smartlist_t *sl, const char *join,
460 size_t join_len, int terminate, size_t *len_out)
462 int i;
463 size_t n = 0;
464 char *r = NULL, *dst, *src;
466 tor_assert(sl);
467 tor_assert(join);
469 if (terminate)
470 n = join_len;
472 for (i = 0; i < sl->num_used; ++i) {
473 n += strlen(sl->list[i]);
474 if (i+1 < sl->num_used) /* avoid double-counting the last one */
475 n += join_len;
477 dst = r = tor_malloc(n+1);
478 for (i = 0; i < sl->num_used; ) {
479 for (src = sl->list[i]; *src; )
480 *dst++ = *src++;
481 if (++i < sl->num_used) {
482 memcpy(dst, join, join_len);
483 dst += join_len;
486 if (terminate) {
487 memcpy(dst, join, join_len);
488 dst += join_len;
490 *dst = '\0';
492 if (len_out)
493 *len_out = dst-r;
494 return r;
497 /** Sort the members of <b>sl</b> into an order defined by
498 * the ordering function <b>compare</b>, which returns less then 0 if a
499 * precedes b, greater than 0 if b precedes a, and 0 if a 'equals' b.
501 void
502 smartlist_sort(smartlist_t *sl, int (*compare)(const void **a, const void **b))
504 if (!sl->num_used)
505 return;
506 qsort(sl->list, sl->num_used, sizeof(void*),
507 (int (*)(const void *,const void*))compare);
510 /** Given a smartlist <b>sl</b> sorted with the function <b>compare</b>,
511 * return the most frequent member in the list. Break ties in favor of
512 * later elements. If the list is empty, return NULL.
514 void *
515 smartlist_get_most_frequent(const smartlist_t *sl,
516 int (*compare)(const void **a, const void **b))
518 const void *most_frequent = NULL;
519 int most_frequent_count = 0;
521 const void *cur = NULL;
522 int i, count=0;
524 if (!sl->num_used)
525 return NULL;
526 for (i = 0; i < sl->num_used; ++i) {
527 const void *item = sl->list[i];
528 if (cur && 0 == compare(&cur, &item)) {
529 ++count;
530 } else {
531 if (cur && count >= most_frequent_count) {
532 most_frequent = cur;
533 most_frequent_count = count;
535 cur = item;
536 count = 1;
539 if (cur && count >= most_frequent_count) {
540 most_frequent = cur;
541 most_frequent_count = count;
543 return (void*)most_frequent;
546 /** Given a sorted smartlist <b>sl</b> and the comparison function used to
547 * sort it, remove all duplicate members. If free_fn is provided, calls
548 * free_fn on each duplicate. Otherwise, just removes them. Preserves order.
550 void
551 smartlist_uniq(smartlist_t *sl,
552 int (*compare)(const void **a, const void **b),
553 void (*free_fn)(void *a))
555 int i;
556 for (i=1; i < sl->num_used; ++i) {
557 if (compare((const void **)&(sl->list[i-1]),
558 (const void **)&(sl->list[i])) == 0) {
559 if (free_fn)
560 free_fn(sl->list[i]);
561 smartlist_del_keeporder(sl, i--);
566 /** Assuming the members of <b>sl</b> are in order, return a pointer to the
567 * member that matches <b>key</b>. Ordering and matching are defined by a
568 * <b>compare</b> function that returns 0 on a match; less than 0 if key is
569 * less than member, and greater than 0 if key is greater then member.
571 void *
572 smartlist_bsearch(smartlist_t *sl, const void *key,
573 int (*compare)(const void *key, const void **member))
575 int found, idx;
576 idx = smartlist_bsearch_idx(sl, key, compare, &found);
577 return found ? smartlist_get(sl, idx) : NULL;
580 /** Assuming the members of <b>sl</b> are in order, return the index of the
581 * member that matches <b>key</b>. If no member matches, return the index of
582 * the first member greater than <b>key</b>, or smartlist_len(sl) if no member
583 * is greater than <b>key</b>. Set <b>found_out</b> to true on a match, to
584 * false otherwise. Ordering and matching are defined by a <b>compare</b>
585 * function that returns 0 on a match; less than 0 if key is less than member,
586 * and greater than 0 if key is greater then member.
589 smartlist_bsearch_idx(const smartlist_t *sl, const void *key,
590 int (*compare)(const void *key, const void **member),
591 int *found_out)
593 int hi, lo, cmp, mid, len, diff;
595 tor_assert(sl);
596 tor_assert(compare);
597 tor_assert(found_out);
599 len = smartlist_len(sl);
601 /* Check for the trivial case of a zero-length list */
602 if (len == 0) {
603 *found_out = 0;
604 /* We already know smartlist_len(sl) is 0 in this case */
605 return 0;
608 /* Okay, we have a real search to do */
609 tor_assert(len > 0);
610 lo = 0;
611 hi = len - 1;
614 * These invariants are always true:
616 * For all i such that 0 <= i < lo, sl[i] < key
617 * For all i such that hi < i <= len, sl[i] > key
620 while (lo <= hi) {
621 diff = hi - lo;
623 * We want mid = (lo + hi) / 2, but that could lead to overflow, so
624 * instead diff = hi - lo (non-negative because of loop condition), and
625 * then hi = lo + diff, mid = (lo + lo + diff) / 2 = lo + (diff / 2).
627 mid = lo + (diff / 2);
628 cmp = compare(key, (const void**) &(sl->list[mid]));
629 if (cmp == 0) {
630 /* sl[mid] == key; we found it */
631 *found_out = 1;
632 return mid;
633 } else if (cmp > 0) {
635 * key > sl[mid] and an index i such that sl[i] == key must
636 * have i > mid if it exists.
640 * Since lo <= mid <= hi, hi can only decrease on each iteration (by
641 * being set to mid - 1) and hi is initially len - 1, mid < len should
642 * always hold, and this is not symmetric with the left end of list
643 * mid > 0 test below. A key greater than the right end of the list
644 * should eventually lead to lo == hi == mid == len - 1, and then
645 * we set lo to len below and fall out to the same exit we hit for
646 * a key in the middle of the list but not matching. Thus, we just
647 * assert for consistency here rather than handle a mid == len case.
649 tor_assert(mid < len);
650 /* Move lo to the element immediately after sl[mid] */
651 lo = mid + 1;
652 } else {
653 /* This should always be true in this case */
654 tor_assert(cmp < 0);
657 * key < sl[mid] and an index i such that sl[i] == key must
658 * have i < mid if it exists.
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);
669 * We were at the beginning of the list and concluded that every
670 * element e compares e > key.
672 *found_out = 0;
673 return 0;
679 * lo > hi; we have no element matching key but we have elements falling
680 * on both sides of it. The lo index points to the first element > key.
682 tor_assert(lo == hi + 1); /* All other cases should have been handled */
683 tor_assert(lo >= 0);
684 tor_assert(lo <= len);
685 tor_assert(hi >= 0);
686 tor_assert(hi <= len);
688 if (lo < len) {
689 cmp = compare(key, (const void **) &(sl->list[lo]));
690 tor_assert(cmp < 0);
691 } else {
692 cmp = compare(key, (const void **) &(sl->list[len-1]));
693 tor_assert(cmp > 0);
696 *found_out = 0;
697 return lo;
700 /** Helper: compare two const char **s. */
701 static int
702 compare_string_ptrs_(const void **_a, const void **_b)
704 return strcmp((const char*)*_a, (const char*)*_b);
707 /** Sort a smartlist <b>sl</b> containing strings into lexically ascending
708 * order. */
709 void
710 smartlist_sort_strings(smartlist_t *sl)
712 smartlist_sort(sl, compare_string_ptrs_);
715 /** Return the most frequent string in the sorted list <b>sl</b> */
716 char *
717 smartlist_get_most_frequent_string(smartlist_t *sl)
719 return smartlist_get_most_frequent(sl, compare_string_ptrs_);
722 /** Remove duplicate strings from a sorted list, and free them with tor_free().
724 void
725 smartlist_uniq_strings(smartlist_t *sl)
727 smartlist_uniq(sl, compare_string_ptrs_, tor_free_);
730 /** Helper: compare two pointers. */
731 static int
732 compare_ptrs_(const void **_a, const void **_b)
734 const void *a = *_a, *b = *_b;
735 if (a<b)
736 return -1;
737 else if (a==b)
738 return 0;
739 else
740 return 1;
743 /** Sort <b>sl</b> in ascending order of the pointers it contains. */
744 void
745 smartlist_sort_pointers(smartlist_t *sl)
747 smartlist_sort(sl, compare_ptrs_);
750 /* Heap-based priority queue implementation for O(lg N) insert and remove.
751 * Recall that the heap property is that, for every index I, h[I] <
752 * H[LEFT_CHILD[I]] and h[I] < H[RIGHT_CHILD[I]].
754 * For us to remove items other than the topmost item, each item must store
755 * its own index within the heap. When calling the pqueue functions, tell
756 * them about the offset of the field that stores the index within the item.
758 * Example:
760 * typedef struct timer_t {
761 * struct timeval tv;
762 * int heap_index;
763 * } timer_t;
765 * static int compare(const void *p1, const void *p2) {
766 * const timer_t *t1 = p1, *t2 = p2;
767 * if (t1->tv.tv_sec < t2->tv.tv_sec) {
768 * return -1;
769 * } else if (t1->tv.tv_sec > t2->tv.tv_sec) {
770 * return 1;
771 * } else {
772 * return t1->tv.tv_usec - t2->tv_usec;
776 * void timer_heap_insert(smartlist_t *heap, timer_t *timer) {
777 * smartlist_pqueue_add(heap, compare, STRUCT_OFFSET(timer_t, heap_index),
778 * timer);
781 * void timer_heap_pop(smartlist_t *heap) {
782 * return smartlist_pqueue_pop(heap, compare,
783 * STRUCT_OFFSET(timer_t, heap_index));
787 /** @{ */
788 /** Functions to manipulate heap indices to find a node's parent and children.
790 * For a 1-indexed array, we would use LEFT_CHILD[x] = 2*x and RIGHT_CHILD[x]
791 * = 2*x + 1. But this is C, so we have to adjust a little. */
792 //#define LEFT_CHILD(i) ( ((i)+1)*2 - 1)
793 //#define RIGHT_CHILD(i) ( ((i)+1)*2 )
794 //#define PARENT(i) ( ((i)+1)/2 - 1)
795 #define LEFT_CHILD(i) ( 2*(i) + 1 )
796 #define RIGHT_CHILD(i) ( 2*(i) + 2 )
797 #define PARENT(i) ( ((i)-1) / 2 )
798 /** }@ */
800 /** @{ */
801 /** Helper macros for heaps: Given a local variable <b>idx_field_offset</b>
802 * set to the offset of an integer index within the heap element structure,
803 * IDX_OF_ITEM(p) gives you the index of p, and IDXP(p) gives you a pointer to
804 * where p's index is stored. Given additionally a local smartlist <b>sl</b>,
805 * UPDATE_IDX(i) sets the index of the element at <b>i</b> to the correct
806 * value (that is, to <b>i</b>).
808 #define IDXP(p) ((int*)STRUCT_VAR_P(p, idx_field_offset))
810 #define UPDATE_IDX(i) do { \
811 void *updated = sl->list[i]; \
812 *IDXP(updated) = i; \
813 } while (0)
815 #define IDX_OF_ITEM(p) (*IDXP(p))
816 /** @} */
818 /** Helper. <b>sl</b> may have at most one violation of the heap property:
819 * the item at <b>idx</b> may be greater than one or both of its children.
820 * Restore the heap property. */
821 static INLINE void
822 smartlist_heapify(smartlist_t *sl,
823 int (*compare)(const void *a, const void *b),
824 int idx_field_offset,
825 int idx)
827 while (1) {
828 int left_idx = LEFT_CHILD(idx);
829 int best_idx;
831 if (left_idx >= sl->num_used)
832 return;
833 if (compare(sl->list[idx],sl->list[left_idx]) < 0)
834 best_idx = idx;
835 else
836 best_idx = left_idx;
837 if (left_idx+1 < sl->num_used &&
838 compare(sl->list[left_idx+1],sl->list[best_idx]) < 0)
839 best_idx = left_idx + 1;
841 if (best_idx == idx) {
842 return;
843 } else {
844 void *tmp = sl->list[idx];
845 sl->list[idx] = sl->list[best_idx];
846 sl->list[best_idx] = tmp;
847 UPDATE_IDX(idx);
848 UPDATE_IDX(best_idx);
850 idx = best_idx;
855 /** Insert <b>item</b> into the heap stored in <b>sl</b>, where order is
856 * determined by <b>compare</b> and the offset of the item in the heap is
857 * stored in an int-typed field at position <b>idx_field_offset</b> within
858 * item.
860 void
861 smartlist_pqueue_add(smartlist_t *sl,
862 int (*compare)(const void *a, const void *b),
863 int idx_field_offset,
864 void *item)
866 int idx;
867 smartlist_add(sl,item);
868 UPDATE_IDX(sl->num_used-1);
870 for (idx = sl->num_used - 1; idx; ) {
871 int parent = PARENT(idx);
872 if (compare(sl->list[idx], sl->list[parent]) < 0) {
873 void *tmp = sl->list[parent];
874 sl->list[parent] = sl->list[idx];
875 sl->list[idx] = tmp;
876 UPDATE_IDX(parent);
877 UPDATE_IDX(idx);
878 idx = parent;
879 } else {
880 return;
885 /** Remove and return the top-priority item from the heap stored in <b>sl</b>,
886 * where order is determined by <b>compare</b> and the item's position is
887 * stored at position <b>idx_field_offset</b> within the item. <b>sl</b> must
888 * not be empty. */
889 void *
890 smartlist_pqueue_pop(smartlist_t *sl,
891 int (*compare)(const void *a, const void *b),
892 int idx_field_offset)
894 void *top;
895 tor_assert(sl->num_used);
897 top = sl->list[0];
898 *IDXP(top)=-1;
899 if (--sl->num_used) {
900 sl->list[0] = sl->list[sl->num_used];
901 UPDATE_IDX(0);
902 smartlist_heapify(sl, compare, idx_field_offset, 0);
904 return top;
907 /** Remove the item <b>item</b> from the heap stored in <b>sl</b>,
908 * where order is determined by <b>compare</b> and the item's position is
909 * stored at position <b>idx_field_offset</b> within the item. <b>sl</b> must
910 * not be empty. */
911 void
912 smartlist_pqueue_remove(smartlist_t *sl,
913 int (*compare)(const void *a, const void *b),
914 int idx_field_offset,
915 void *item)
917 int idx = IDX_OF_ITEM(item);
918 tor_assert(idx >= 0);
919 tor_assert(sl->list[idx] == item);
920 --sl->num_used;
921 *IDXP(item) = -1;
922 if (idx == sl->num_used) {
923 return;
924 } else {
925 sl->list[idx] = sl->list[sl->num_used];
926 UPDATE_IDX(idx);
927 smartlist_heapify(sl, compare, idx_field_offset, idx);
931 /** Assert that the heap property is correctly maintained by the heap stored
932 * in <b>sl</b>, where order is determined by <b>compare</b>. */
933 void
934 smartlist_pqueue_assert_ok(smartlist_t *sl,
935 int (*compare)(const void *a, const void *b),
936 int idx_field_offset)
938 int i;
939 for (i = sl->num_used - 1; i >= 0; --i) {
940 if (i>0)
941 tor_assert(compare(sl->list[PARENT(i)], sl->list[i]) <= 0);
942 tor_assert(IDX_OF_ITEM(sl->list[i]) == i);
946 /** Helper: compare two DIGEST_LEN digests. */
947 static int
948 compare_digests_(const void **_a, const void **_b)
950 return tor_memcmp((const char*)*_a, (const char*)*_b, DIGEST_LEN);
953 /** Sort the list of DIGEST_LEN-byte digests into ascending order. */
954 void
955 smartlist_sort_digests(smartlist_t *sl)
957 smartlist_sort(sl, compare_digests_);
960 /** Remove duplicate digests from a sorted list, and free them with tor_free().
962 void
963 smartlist_uniq_digests(smartlist_t *sl)
965 smartlist_uniq(sl, compare_digests_, tor_free_);
968 /** Helper: compare two DIGEST256_LEN digests. */
969 static int
970 compare_digests256_(const void **_a, const void **_b)
972 return tor_memcmp((const char*)*_a, (const char*)*_b, DIGEST256_LEN);
975 /** Sort the list of DIGEST256_LEN-byte digests into ascending order. */
976 void
977 smartlist_sort_digests256(smartlist_t *sl)
979 smartlist_sort(sl, compare_digests256_);
982 /** Return the most frequent member of the sorted list of DIGEST256_LEN
983 * digests in <b>sl</b> */
984 char *
985 smartlist_get_most_frequent_digest256(smartlist_t *sl)
987 return smartlist_get_most_frequent(sl, compare_digests256_);
990 /** Remove duplicate 256-bit digests from a sorted list, and free them with
991 * tor_free().
993 void
994 smartlist_uniq_digests256(smartlist_t *sl)
996 smartlist_uniq(sl, compare_digests256_, tor_free_);
999 /** Helper: Declare an entry type and a map type to implement a mapping using
1000 * ht.h. The map type will be called <b>maptype</b>. The key part of each
1001 * entry is declared using the C declaration <b>keydecl</b>. All functions
1002 * and types associated with the map get prefixed with <b>prefix</b> */
1003 #define DEFINE_MAP_STRUCTS(maptype, keydecl, prefix) \
1004 typedef struct prefix ## entry_t { \
1005 HT_ENTRY(prefix ## entry_t) node; \
1006 void *val; \
1007 keydecl; \
1008 } prefix ## entry_t; \
1009 struct maptype { \
1010 HT_HEAD(prefix ## impl, prefix ## entry_t) head; \
1013 DEFINE_MAP_STRUCTS(strmap_t, char *key, strmap_);
1014 DEFINE_MAP_STRUCTS(digestmap_t, char key[DIGEST_LEN], digestmap_);
1016 /** Helper: compare strmap_entry_t objects by key value. */
1017 static INLINE int
1018 strmap_entries_eq(const strmap_entry_t *a, const strmap_entry_t *b)
1020 return !strcmp(a->key, b->key);
1023 /** Helper: return a hash value for a strmap_entry_t. */
1024 static INLINE unsigned int
1025 strmap_entry_hash(const strmap_entry_t *a)
1027 return (unsigned) siphash24g(a->key, strlen(a->key));
1030 /** Helper: compare digestmap_entry_t objects by key value. */
1031 static INLINE int
1032 digestmap_entries_eq(const digestmap_entry_t *a, const digestmap_entry_t *b)
1034 return tor_memeq(a->key, b->key, DIGEST_LEN);
1037 /** Helper: return a hash value for a digest_map_t. */
1038 static INLINE unsigned int
1039 digestmap_entry_hash(const digestmap_entry_t *a)
1041 return (unsigned) siphash24g(a->key, DIGEST_LEN);
1044 HT_PROTOTYPE(strmap_impl, strmap_entry_t, node, strmap_entry_hash,
1045 strmap_entries_eq)
1046 HT_GENERATE(strmap_impl, strmap_entry_t, node, strmap_entry_hash,
1047 strmap_entries_eq, 0.6, malloc, realloc, free)
1049 HT_PROTOTYPE(digestmap_impl, digestmap_entry_t, node, digestmap_entry_hash,
1050 digestmap_entries_eq)
1051 HT_GENERATE(digestmap_impl, digestmap_entry_t, node, digestmap_entry_hash,
1052 digestmap_entries_eq, 0.6, malloc, realloc, free)
1054 /** Constructor to create a new empty map from strings to void*'s.
1056 strmap_t *
1057 strmap_new(void)
1059 strmap_t *result;
1060 result = tor_malloc(sizeof(strmap_t));
1061 HT_INIT(strmap_impl, &result->head);
1062 return result;
1065 /** Constructor to create a new empty map from digests to void*'s.
1067 digestmap_t *
1068 digestmap_new(void)
1070 digestmap_t *result;
1071 result = tor_malloc(sizeof(digestmap_t));
1072 HT_INIT(digestmap_impl, &result->head);
1073 return result;
1076 /** Set the current value for <b>key</b> to <b>val</b>. Returns the previous
1077 * value for <b>key</b> if one was set, or NULL if one was not.
1079 * This function makes a copy of <b>key</b> if necessary, but not of
1080 * <b>val</b>.
1082 void *
1083 strmap_set(strmap_t *map, const char *key, void *val)
1085 strmap_entry_t *resolve;
1086 strmap_entry_t search;
1087 void *oldval;
1088 tor_assert(map);
1089 tor_assert(key);
1090 tor_assert(val);
1091 search.key = (char*)key;
1092 resolve = HT_FIND(strmap_impl, &map->head, &search);
1093 if (resolve) {
1094 oldval = resolve->val;
1095 resolve->val = val;
1096 return oldval;
1097 } else {
1098 resolve = tor_malloc_zero(sizeof(strmap_entry_t));
1099 resolve->key = tor_strdup(key);
1100 resolve->val = val;
1101 tor_assert(!HT_FIND(strmap_impl, &map->head, resolve));
1102 HT_INSERT(strmap_impl, &map->head, resolve);
1103 return NULL;
1107 #define OPTIMIZED_DIGESTMAP_SET
1109 /** Like strmap_set() above but for digestmaps. */
1110 void *
1111 digestmap_set(digestmap_t *map, const char *key, void *val)
1113 #ifndef OPTIMIZED_DIGESTMAP_SET
1114 digestmap_entry_t *resolve;
1115 #endif
1116 digestmap_entry_t search;
1117 void *oldval;
1118 tor_assert(map);
1119 tor_assert(key);
1120 tor_assert(val);
1121 memcpy(&search.key, key, DIGEST_LEN);
1122 #ifndef OPTIMIZED_DIGESTMAP_SET
1123 resolve = HT_FIND(digestmap_impl, &map->head, &search);
1124 if (resolve) {
1125 oldval = resolve->val;
1126 resolve->val = val;
1127 return oldval;
1128 } else {
1129 resolve = tor_malloc_zero(sizeof(digestmap_entry_t));
1130 memcpy(resolve->key, key, DIGEST_LEN);
1131 resolve->val = val;
1132 HT_INSERT(digestmap_impl, &map->head, resolve);
1133 return NULL;
1135 #else
1136 /* We spend up to 5% of our time in this function, so the code below is
1137 * meant to optimize the check/alloc/set cycle by avoiding the two trips to
1138 * the hash table that we do in the unoptimized code above. (Each of
1139 * HT_INSERT and HT_FIND calls HT_SET_HASH and HT_FIND_P.)
1141 HT_FIND_OR_INSERT_(digestmap_impl, node, digestmap_entry_hash, &(map->head),
1142 digestmap_entry_t, &search, ptr,
1144 /* we found an entry. */
1145 oldval = (*ptr)->val;
1146 (*ptr)->val = val;
1147 return oldval;
1150 /* We didn't find the entry. */
1151 digestmap_entry_t *newent =
1152 tor_malloc_zero(sizeof(digestmap_entry_t));
1153 memcpy(newent->key, key, DIGEST_LEN);
1154 newent->val = val;
1155 HT_FOI_INSERT_(node, &(map->head), &search, newent, ptr);
1156 return NULL;
1158 #endif
1161 /** Return the current value associated with <b>key</b>, or NULL if no
1162 * value is set.
1164 void *
1165 strmap_get(const strmap_t *map, const char *key)
1167 strmap_entry_t *resolve;
1168 strmap_entry_t search;
1169 tor_assert(map);
1170 tor_assert(key);
1171 search.key = (char*)key;
1172 resolve = HT_FIND(strmap_impl, &map->head, &search);
1173 if (resolve) {
1174 return resolve->val;
1175 } else {
1176 return NULL;
1180 /** Like strmap_get() above but for digestmaps. */
1181 void *
1182 digestmap_get(const digestmap_t *map, const char *key)
1184 digestmap_entry_t *resolve;
1185 digestmap_entry_t search;
1186 tor_assert(map);
1187 tor_assert(key);
1188 memcpy(&search.key, key, DIGEST_LEN);
1189 resolve = HT_FIND(digestmap_impl, &map->head, &search);
1190 if (resolve) {
1191 return resolve->val;
1192 } else {
1193 return NULL;
1197 /** Remove the value currently associated with <b>key</b> from the map.
1198 * Return the value if one was set, or NULL if there was no entry for
1199 * <b>key</b>.
1201 * Note: you must free any storage associated with the returned value.
1203 void *
1204 strmap_remove(strmap_t *map, const char *key)
1206 strmap_entry_t *resolve;
1207 strmap_entry_t search;
1208 void *oldval;
1209 tor_assert(map);
1210 tor_assert(key);
1211 search.key = (char*)key;
1212 resolve = HT_REMOVE(strmap_impl, &map->head, &search);
1213 if (resolve) {
1214 oldval = resolve->val;
1215 tor_free(resolve->key);
1216 tor_free(resolve);
1217 return oldval;
1218 } else {
1219 return NULL;
1223 /** Like strmap_remove() above but for digestmaps. */
1224 void *
1225 digestmap_remove(digestmap_t *map, const char *key)
1227 digestmap_entry_t *resolve;
1228 digestmap_entry_t search;
1229 void *oldval;
1230 tor_assert(map);
1231 tor_assert(key);
1232 memcpy(&search.key, key, DIGEST_LEN);
1233 resolve = HT_REMOVE(digestmap_impl, &map->head, &search);
1234 if (resolve) {
1235 oldval = resolve->val;
1236 tor_free(resolve);
1237 return oldval;
1238 } else {
1239 return NULL;
1243 /** Same as strmap_set, but first converts <b>key</b> to lowercase. */
1244 void *
1245 strmap_set_lc(strmap_t *map, const char *key, void *val)
1247 /* We could be a little faster by using strcasecmp instead, and a separate
1248 * type, but I don't think it matters. */
1249 void *v;
1250 char *lc_key = tor_strdup(key);
1251 tor_strlower(lc_key);
1252 v = strmap_set(map,lc_key,val);
1253 tor_free(lc_key);
1254 return v;
1257 /** Same as strmap_get, but first converts <b>key</b> to lowercase. */
1258 void *
1259 strmap_get_lc(const strmap_t *map, const char *key)
1261 void *v;
1262 char *lc_key = tor_strdup(key);
1263 tor_strlower(lc_key);
1264 v = strmap_get(map,lc_key);
1265 tor_free(lc_key);
1266 return v;
1269 /** Same as strmap_remove, but first converts <b>key</b> to lowercase */
1270 void *
1271 strmap_remove_lc(strmap_t *map, const char *key)
1273 void *v;
1274 char *lc_key = tor_strdup(key);
1275 tor_strlower(lc_key);
1276 v = strmap_remove(map,lc_key);
1277 tor_free(lc_key);
1278 return v;
1281 /** return an <b>iterator</b> pointer to the front of a map.
1283 * Iterator example:
1285 * \code
1286 * // uppercase values in "map", removing empty values.
1288 * strmap_iter_t *iter;
1289 * const char *key;
1290 * void *val;
1291 * char *cp;
1293 * for (iter = strmap_iter_init(map); !strmap_iter_done(iter); ) {
1294 * strmap_iter_get(iter, &key, &val);
1295 * cp = (char*)val;
1296 * if (!*cp) {
1297 * iter = strmap_iter_next_rmv(map,iter);
1298 * free(val);
1299 * } else {
1300 * for (;*cp;cp++) *cp = TOR_TOUPPER(*cp);
1301 * iter = strmap_iter_next(map,iter);
1304 * \endcode
1307 strmap_iter_t *
1308 strmap_iter_init(strmap_t *map)
1310 tor_assert(map);
1311 return HT_START(strmap_impl, &map->head);
1314 /** Start iterating through <b>map</b>. See strmap_iter_init() for example. */
1315 digestmap_iter_t *
1316 digestmap_iter_init(digestmap_t *map)
1318 tor_assert(map);
1319 return HT_START(digestmap_impl, &map->head);
1322 /** Advance the iterator <b>iter</b> for <b>map</b> a single step to the next
1323 * entry, and return its new value. */
1324 strmap_iter_t *
1325 strmap_iter_next(strmap_t *map, strmap_iter_t *iter)
1327 tor_assert(map);
1328 tor_assert(iter);
1329 return HT_NEXT(strmap_impl, &map->head, iter);
1332 /** Advance the iterator <b>iter</b> for map a single step to the next entry,
1333 * and return its new value. */
1334 digestmap_iter_t *
1335 digestmap_iter_next(digestmap_t *map, digestmap_iter_t *iter)
1337 tor_assert(map);
1338 tor_assert(iter);
1339 return HT_NEXT(digestmap_impl, &map->head, iter);
1342 /** Advance the iterator <b>iter</b> a single step to the next entry, removing
1343 * the current entry, and return its new value.
1345 strmap_iter_t *
1346 strmap_iter_next_rmv(strmap_t *map, strmap_iter_t *iter)
1348 strmap_entry_t *rmv;
1349 tor_assert(map);
1350 tor_assert(iter);
1351 tor_assert(*iter);
1352 rmv = *iter;
1353 iter = HT_NEXT_RMV(strmap_impl, &map->head, iter);
1354 tor_free(rmv->key);
1355 tor_free(rmv);
1356 return iter;
1359 /** Advance the iterator <b>iter</b> a single step to the next entry, removing
1360 * the current entry, and return its new value.
1362 digestmap_iter_t *
1363 digestmap_iter_next_rmv(digestmap_t *map, digestmap_iter_t *iter)
1365 digestmap_entry_t *rmv;
1366 tor_assert(map);
1367 tor_assert(iter);
1368 tor_assert(*iter);
1369 rmv = *iter;
1370 iter = HT_NEXT_RMV(digestmap_impl, &map->head, iter);
1371 tor_free(rmv);
1372 return iter;
1375 /** Set *<b>keyp</b> and *<b>valp</b> to the current entry pointed to by
1376 * iter. */
1377 void
1378 strmap_iter_get(strmap_iter_t *iter, const char **keyp, void **valp)
1380 tor_assert(iter);
1381 tor_assert(*iter);
1382 tor_assert(keyp);
1383 tor_assert(valp);
1384 *keyp = (*iter)->key;
1385 *valp = (*iter)->val;
1388 /** Set *<b>keyp</b> and *<b>valp</b> to the current entry pointed to by
1389 * iter. */
1390 void
1391 digestmap_iter_get(digestmap_iter_t *iter, const char **keyp, void **valp)
1393 tor_assert(iter);
1394 tor_assert(*iter);
1395 tor_assert(keyp);
1396 tor_assert(valp);
1397 *keyp = (*iter)->key;
1398 *valp = (*iter)->val;
1401 /** Return true iff <b>iter</b> has advanced past the last entry of
1402 * <b>map</b>. */
1404 strmap_iter_done(strmap_iter_t *iter)
1406 return iter == NULL;
1409 /** Return true iff <b>iter</b> has advanced past the last entry of
1410 * <b>map</b>. */
1412 digestmap_iter_done(digestmap_iter_t *iter)
1414 return iter == NULL;
1417 /** Remove all entries from <b>map</b>, and deallocate storage for those
1418 * entries. If free_val is provided, it is invoked on every value in
1419 * <b>map</b>.
1421 void
1422 strmap_free(strmap_t *map, void (*free_val)(void*))
1424 strmap_entry_t **ent, **next, *this;
1425 if (!map)
1426 return;
1428 for (ent = HT_START(strmap_impl, &map->head); ent != NULL; ent = next) {
1429 this = *ent;
1430 next = HT_NEXT_RMV(strmap_impl, &map->head, ent);
1431 tor_free(this->key);
1432 if (free_val)
1433 free_val(this->val);
1434 tor_free(this);
1436 tor_assert(HT_EMPTY(&map->head));
1437 HT_CLEAR(strmap_impl, &map->head);
1438 tor_free(map);
1441 /** Remove all entries from <b>map</b>, and deallocate storage for those
1442 * entries. If free_val is provided, it is invoked on every value in
1443 * <b>map</b>.
1445 void
1446 digestmap_free(digestmap_t *map, void (*free_val)(void*))
1448 digestmap_entry_t **ent, **next, *this;
1449 if (!map)
1450 return;
1451 for (ent = HT_START(digestmap_impl, &map->head); ent != NULL; ent = next) {
1452 this = *ent;
1453 next = HT_NEXT_RMV(digestmap_impl, &map->head, ent);
1454 if (free_val)
1455 free_val(this->val);
1456 tor_free(this);
1458 tor_assert(HT_EMPTY(&map->head));
1459 HT_CLEAR(digestmap_impl, &map->head);
1460 tor_free(map);
1463 /** Fail with an assertion error if anything has gone wrong with the internal
1464 * representation of <b>map</b>. */
1465 void
1466 strmap_assert_ok(const strmap_t *map)
1468 tor_assert(!strmap_impl_HT_REP_IS_BAD_(&map->head));
1470 /** Fail with an assertion error if anything has gone wrong with the internal
1471 * representation of <b>map</b>. */
1472 void
1473 digestmap_assert_ok(const digestmap_t *map)
1475 tor_assert(!digestmap_impl_HT_REP_IS_BAD_(&map->head));
1478 /** Return true iff <b>map</b> has no entries. */
1480 strmap_isempty(const strmap_t *map)
1482 return HT_EMPTY(&map->head);
1485 /** Return true iff <b>map</b> has no entries. */
1487 digestmap_isempty(const digestmap_t *map)
1489 return HT_EMPTY(&map->head);
1492 /** Return the number of items in <b>map</b>. */
1494 strmap_size(const strmap_t *map)
1496 return HT_SIZE(&map->head);
1499 /** Return the number of items in <b>map</b>. */
1501 digestmap_size(const digestmap_t *map)
1503 return HT_SIZE(&map->head);
1506 /** Declare a function called <b>funcname</b> that acts as a find_nth_FOO
1507 * function for an array of type <b>elt_t</b>*.
1509 * NOTE: The implementation kind of sucks: It's O(n log n), whereas finding
1510 * the kth element of an n-element list can be done in O(n). Then again, this
1511 * implementation is not in critical path, and it is obviously correct. */
1512 #define IMPLEMENT_ORDER_FUNC(funcname, elt_t) \
1513 static int \
1514 _cmp_ ## elt_t(const void *_a, const void *_b) \
1516 const elt_t *a = _a, *b = _b; \
1517 if (*a<*b) \
1518 return -1; \
1519 else if (*a>*b) \
1520 return 1; \
1521 else \
1522 return 0; \
1524 elt_t \
1525 funcname(elt_t *array, int n_elements, int nth) \
1527 tor_assert(nth >= 0); \
1528 tor_assert(nth < n_elements); \
1529 qsort(array, n_elements, sizeof(elt_t), _cmp_ ##elt_t); \
1530 return array[nth]; \
1533 IMPLEMENT_ORDER_FUNC(find_nth_int, int)
1534 IMPLEMENT_ORDER_FUNC(find_nth_time, time_t)
1535 IMPLEMENT_ORDER_FUNC(find_nth_double, double)
1536 IMPLEMENT_ORDER_FUNC(find_nth_uint32, uint32_t)
1537 IMPLEMENT_ORDER_FUNC(find_nth_int32, int32_t)
1538 IMPLEMENT_ORDER_FUNC(find_nth_long, long)
1540 /** Return a newly allocated digestset_t, optimized to hold a total of
1541 * <b>max_elements</b> digests with a reasonably low false positive weight. */
1542 digestset_t *
1543 digestset_new(int max_elements)
1545 /* The probability of false positives is about P=(1 - exp(-kn/m))^k, where k
1546 * is the number of hash functions per entry, m is the bits in the array,
1547 * and n is the number of elements inserted. For us, k==4, n<=max_elements,
1548 * and m==n_bits= approximately max_elements*32. This gives
1549 * P<(1-exp(-4*n/(32*n)))^4 == (1-exp(1/-8))^4 == .00019
1551 * It would be more optimal in space vs false positives to get this false
1552 * positive rate by going for k==13, and m==18.5n, but we also want to
1553 * conserve CPU, and k==13 is pretty big.
1555 int n_bits = 1u << (tor_log2(max_elements)+5);
1556 digestset_t *r = tor_malloc(sizeof(digestset_t));
1557 r->mask = n_bits - 1;
1558 r->ba = bitarray_init_zero(n_bits);
1559 return r;
1562 /** Free all storage held in <b>set</b>. */
1563 void
1564 digestset_free(digestset_t *set)
1566 if (!set)
1567 return;
1568 bitarray_free(set->ba);
1569 tor_free(set);