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 */
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.
17 #include "container.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
*,
34 smartlist_t
*sl
= tor_malloc(sizeof(smartlist_t
));
36 sl
->capacity
= SMARTLIST_DEFAULT_CAPACITY
;
37 sl
->list
= tor_calloc(sizeof(void *), sl
->capacity
);
41 /** Deallocate a smartlist. Does not release storage associated with the
45 smartlist_free
,(smartlist_t
*sl
))
53 /** Remove all elements from the list.
56 smartlist_clear(smartlist_t
*sl
)
58 memset(sl
->list
, 0, sizeof(void *) * sl
->num_used
);
62 #if SIZE_MAX < INT_MAX
63 #error "We don't support systems where size_t is smaller than int."
66 /** Make sure that <b>sl</b> can hold at least <b>size</b> entries. */
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)
74 #define MAX_CAPACITY (int)((SIZE_MAX / (sizeof(void*))))
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
;
87 sl
->list
= tor_reallocarray(sl
->list
, sizeof(void *),
89 memset(sl
->list
+ sl
->capacity
, 0,
90 sizeof(void *) * (higher
- sl
->capacity
));
91 sl
->capacity
= (int) higher
;
93 #undef ASSERT_CAPACITY
97 /** Append element to the end of the list. */
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. */
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
122 smartlist_remove(smartlist_t
*sl
, const void *element
)
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 */
138 smartlist_remove_keeporder(smartlist_t
*sl
, const void *element
)
140 int i
, j
, num_used_orig
= sl
->num_used
;
144 for (i
=j
=0; j
< num_used_orig
; ++j
) {
145 if (sl
->list
[j
] == element
) {
148 sl
->list
[i
++] = sl
->list
[j
];
153 /** If <b>sl</b> is nonempty, remove and return the final element. Otherwise,
156 smartlist_pop_last(smartlist_t
*sl
)
160 void *tmp
= sl
->list
[--sl
->num_used
];
161 sl
->list
[sl
->num_used
] = NULL
;
167 /** Reverse the order of the items in <b>sl</b>. */
169 smartlist_reverse(smartlist_t
*sl
)
174 for (i
= 0, j
= sl
->num_used
-1; i
< j
; ++i
, --j
) {
176 sl
->list
[i
] = sl
->list
[j
];
181 /** If there are any strings in sl equal to element, remove and free them.
182 * Does not preserve order. */
184 smartlist_string_remove(smartlist_t
*sl
, const char *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
)
205 for (i
=0; i
< sl
->num_used
; i
++)
206 if (sl
->list
[i
] == element
)
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
)
219 for (i
=0; i
< sl
->num_used
; i
++)
220 if (strcmp((const char*)sl
->list
[i
],element
)==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
)
232 for (i
=0; i
< sl
->num_used
; i
++)
233 if (strcmp((const char*)sl
->list
[i
],element
)==0)
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
)
245 for (i
=0; i
< sl
->num_used
; i
++)
246 if (element
== sl
->list
[i
])
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
)
259 for (i
=0; i
< sl
->num_used
; i
++)
260 if (strcasecmp((const char*)sl
->list
[i
],element
)==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
)
285 if (smartlist_len(sl1
) != smartlist_len(sl2
))
287 SMARTLIST_FOREACH(sl1
, const char *, cp1
, {
288 const char *cp2
= smartlist_get(sl2
, cp1_sl_idx
);
289 if (strcmp(cp1
, cp2
))
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
)
304 if (smartlist_len(sl1
) != smartlist_len(sl2
))
306 SMARTLIST_FOREACH(sl1
, int *, cp1
, {
307 int *cp2
= smartlist_get(sl2
, cp1_sl_idx
);
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
)
322 for (i
=0; i
< sl
->num_used
; i
++)
323 if (tor_memeq((const char*)sl
->list
[i
],element
,DIGEST_LEN
))
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
)
334 for (i
=0; i
< sl2
->num_used
; i
++)
335 if (smartlist_contains(sl1
, sl2
->list
[i
]))
340 /** Remove every element E of sl1 such that !smartlist_contains(sl2,E).
341 * Does not preserve the order of sl1.
344 smartlist_intersect(smartlist_t
*sl1
, const smartlist_t
*sl2
)
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.
359 smartlist_subtract(smartlist_t
*sl1
, const smartlist_t
*sl2
)
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.
370 smartlist_del(smartlist_t
*sl
, int idx
)
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.
384 smartlist_del_keeporder(smartlist_t
*sl
, int idx
)
388 tor_assert(idx
< 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
400 smartlist_insert(smartlist_t
*sl
, int idx
, void *val
)
404 tor_assert(idx
<= sl
->num_used
);
405 if (idx
== sl
->num_used
) {
406 smartlist_add(sl
, val
);
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
));
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>&SPLIT_SKIP_SPACE is true, remove initial and
424 * trailing space from each entry.
425 * If <b>flags</b>&SPLIT_IGNORE_BLANK is true, remove any entries
427 * If <b>flags</b>&SPLIT_STRIP_SPACE is true, strip spaces from each
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
,
437 const char *cp
, *end
, *next
;
445 if (flags
&SPLIT_SKIP_SPACE
) {
446 while (TOR_ISSPACE(*cp
)) ++cp
;
449 if (max
>0 && n
== max
-1) {
450 end
= strchr(cp
,'\0');
452 end
= strstr(cp
,sep
);
454 end
= strchr(cp
,'\0');
456 for (end
= cp
; *end
&& *end
!= '\t' && *end
!= ' '; ++end
)
465 next
= end
+strlen(sep
);
468 while (*next
== '\t' || *next
== ' ')
472 if (flags
&SPLIT_SKIP_SPACE
) {
473 while (end
> cp
&& TOR_ISSPACE(*(end
-1)))
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
);
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.
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
511 smartlist_join_strings2(smartlist_t
*sl
, const char *join
,
512 size_t join_len
, int terminate
, size_t *len_out
)
516 char *r
= NULL
, *dst
, *src
;
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 */
529 dst
= r
= tor_malloc(n
+1);
530 for (i
= 0; i
< sl
->num_used
; ) {
531 for (src
= sl
->list
[i
]; *src
; )
533 if (++i
< sl
->num_used
) {
534 memcpy(dst
, join
, join_len
);
539 memcpy(dst
, join
, join_len
);
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.
554 smartlist_sort(smartlist_t
*sl
, int (*compare
)(const void **a
, const void **b
))
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.
568 smartlist_get_most_frequent_(const smartlist_t
*sl
,
569 int (*compare
)(const void **a
, const void **b
),
572 const void *most_frequent
= NULL
;
573 int most_frequent_count
= 0;
575 const void *cur
= NULL
;
583 for (i
= 0; i
< sl
->num_used
; ++i
) {
584 const void *item
= sl
->list
[i
];
585 if (cur
&& 0 == compare(&cur
, &item
)) {
588 if (cur
&& count
>= most_frequent_count
) {
590 most_frequent_count
= count
;
596 if (cur
&& count
>= most_frequent_count
) {
598 most_frequent_count
= count
;
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.
610 smartlist_uniq(smartlist_t
*sl
,
611 int (*compare
)(const void **a
, const void **b
),
612 void (*free_fn
)(void *a
))
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) {
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.
631 smartlist_bsearch(smartlist_t
*sl
, const void *key
,
632 int (*compare
)(const void *key
, const void **member
))
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
),
652 int hi
, lo
, cmp
, mid
, len
, diff
;
656 tor_assert(found_out
);
658 len
= smartlist_len(sl
);
660 /* Check for the trivial case of a zero-length list */
663 /* We already know smartlist_len(sl) is 0 in this case */
667 /* Okay, we have a real search to do */
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
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
]));
689 /* sl[mid] == key; we found it */
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] */
712 /* This should always be true in this case */
716 * key < sl[mid] and an index i such that sl[i] == key must
717 * have i < mid if it exists.
721 /* Normal case, move hi to the element immediately before sl[mid] */
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.
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 */
743 tor_assert(lo
<= len
);
745 tor_assert(hi
<= len
);
748 cmp
= compare(key
, (const void **) &(sl
->list
[lo
]));
751 cmp
= compare(key
, (const void **) &(sl
->list
[len
-1]));
759 /** Helper: compare two const char **s. */
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
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> */
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.
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().
794 smartlist_uniq_strings(smartlist_t
*sl
)
796 smartlist_uniq(sl
, compare_string_ptrs_
, tor_free_
);
799 /** Helper: compare two pointers. */
801 compare_ptrs_(const void **_a
, const void **_b
)
803 const void *a
= *_a
, *b
= *_b
;
812 /** Sort <b>sl</b> in ascending order of the pointers it contains. */
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.
829 * typedef struct 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) {
838 * } else if (t1->tv.tv_sec > t2->tv.tv_sec) {
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),
850 * void timer_heap_pop(smartlist_t *heap) {
851 * return smartlist_pqueue_pop(heap, compare,
852 * STRUCT_OFFSET(timer_t, heap_index));
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 )
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; \
892 #define IDX_OF_ITEM(p) (*IDXP(p))
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. */
899 smartlist_heapify(smartlist_t
*sl
,
900 int (*compare
)(const void *a
, const void *b
),
901 int idx_field_offset
,
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). */
913 int left_idx
= LEFT_CHILD(idx
);
916 if (left_idx
>= sl
->num_used
)
918 if (compare(sl
->list
[idx
],sl
->list
[left_idx
]) < 0)
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
) {
929 void *tmp
= sl
->list
[idx
];
930 sl
->list
[idx
] = sl
->list
[best_idx
];
931 sl
->list
[best_idx
] = tmp
;
933 UPDATE_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
946 smartlist_pqueue_add(smartlist_t
*sl
,
947 int (*compare
)(const void *a
, const void *b
),
948 int idx_field_offset
,
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
];
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
975 smartlist_pqueue_pop(smartlist_t
*sl
,
976 int (*compare
)(const void *a
, const void *b
),
977 int idx_field_offset
)
980 tor_assert(sl
->num_used
);
984 if (--sl
->num_used
) {
985 sl
->list
[0] = sl
->list
[sl
->num_used
];
986 sl
->list
[sl
->num_used
] = NULL
;
988 smartlist_heapify(sl
, compare
, idx_field_offset
, 0);
990 sl
->list
[sl
->num_used
] = NULL
;
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
999 smartlist_pqueue_remove(smartlist_t
*sl
,
1000 int (*compare
)(const void *a
, const void *b
),
1001 int idx_field_offset
,
1004 int idx
= IDX_OF_ITEM(item
);
1005 tor_assert(idx
>= 0);
1006 tor_assert(sl
->list
[idx
] == item
);
1009 if (idx
== sl
->num_used
) {
1010 sl
->list
[sl
->num_used
] = NULL
;
1013 sl
->list
[idx
] = sl
->list
[sl
->num_used
];
1014 sl
->list
[sl
->num_used
] = NULL
;
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>. */
1023 smartlist_pqueue_assert_ok(smartlist_t
*sl
,
1024 int (*compare
)(const void *a
, const void *b
),
1025 int idx_field_offset
)
1028 for (i
= sl
->num_used
- 1; i
>= 0; --i
) {
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. */
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. */
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().
1052 smartlist_uniq_digests(smartlist_t
*sl
)
1054 smartlist_uniq(sl
, compare_digests_
, tor_free_
);
1057 /** Helper: compare two DIGEST256_LEN digests. */
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. */
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> */
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
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; \
1097 } prefix ## entry_t; \
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. */
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. */
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. */
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
,
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_
)
1167 strmap_entry_free(strmap_entry_t
*ent
)
1173 digestmap_entry_free(digestmap_entry_t
*ent
)
1178 digest256map_entry_free(digest256map_entry_t
*ent
)
1184 strmap_assign_tmp_key(strmap_entry_t
*ent
, const char *key
)
1186 ent
->key
= (char*)key
;
1189 digestmap_assign_tmp_key(digestmap_entry_t
*ent
, const char *key
)
1191 memcpy(ent
->key
, key
, DIGEST_LEN
);
1194 digest256map_assign_tmp_key(digest256map_entry_t
*ent
, const uint8_t *key
)
1196 memcpy(ent
->key
, key
, DIGEST256_LEN
);
1199 strmap_assign_key(strmap_entry_t
*ent
, const char *key
)
1201 ent
->key
= tor_strdup(key
);
1204 digestmap_assign_key(digestmap_entry_t
*ent
, const char *key
)
1206 memcpy(ent
->key
, key
, DIGEST_LEN
);
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)) \
1228 result = tor_malloc(sizeof(maptype)); \
1229 HT_INIT(prefix##_impl, &result->head); \
1233 /** Return the item from <b>map</b> whose key matches <b>key</b>, or \
1234 * NULL if no such value exists. */ \
1236 prefix##_get(const maptype *map, const keytype key) \
1238 prefix ##_entry_t *resolve; \
1239 prefix ##_entry_t search; \
1242 prefix ##_assign_tmp_key(&search, key); \
1243 resolve = HT_FIND(prefix ##_impl, &map->head, &search); \
1245 return resolve->val; \
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. */ \
1254 prefix##_set(maptype *map, const keytype key, void *val) \
1256 prefix##_entry_t search; \
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, \
1269 prefix##_entry_t, &search, ptr, \
1271 /* we found an entry. */ \
1272 oldval = (*ptr)->val; \
1273 (*ptr)->val = val; \
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); \
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 \
1292 * Note: you must free any storage associated with the returned value. \
1295 prefix##_remove(maptype *map, const keytype key) \
1297 prefix##_entry_t *resolve; \
1298 prefix##_entry_t search; \
1302 prefix##_assign_tmp_key(&search, key); \
1303 resolve = HT_REMOVE(prefix##_impl, &map->head, &search); \
1305 oldval = resolve->val; \
1306 prefix##_entry_free(resolve); \
1313 /** Return the number of elements in <b>map</b>. */ \
1315 prefix##_size(const maptype *map) \
1317 return HT_SIZE(&map->head); \
1320 /** Return true iff <b>map</b> has no entries. */ \
1322 prefix##_isempty(const maptype *map) \
1324 return HT_EMPTY(&map->head); \
1327 /** Assert that <b>map</b> is not corrupt. */ \
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 \
1338 prefix##_free, (maptype *map, void (*free_val)(void*))) \
1340 prefix##_entry_t **ent, **next, *this; \
1343 for (ent = HT_START(prefix##_impl, &map->head); ent != NULL; \
1346 next = HT_NEXT_RMV(prefix##_impl, &map->head, ent); \
1348 free_val(this->val); \
1349 prefix##_entry_free(this); \
1351 tor_assert(HT_EMPTY(&map->head)); \
1352 HT_CLEAR(prefix##_impl, &map->head); \
1356 /** return an <b>iterator</b> pointer to the front of a map. \
1358 * Iterator example: \
1361 * // uppercase values in "map", removing empty values. \
1363 * strmap_iter_t *iter; \
1364 * const char *key; \
1368 * for (iter = strmap_iter_init(map); !strmap_iter_done(iter); ) { \
1369 * strmap_iter_get(iter, &key, &val); \
1370 * cp = (char*)val; \
1372 * iter = strmap_iter_next_rmv(map,iter); \
1375 * for (;*cp;cp++) *cp = TOR_TOUPPER(*cp); \
1378 prefix##_iter_init(maptype *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. */ \
1387 prefix##_iter_next(maptype *map, prefix##_iter_t *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. */ \
1396 prefix##_iter_next_rmv(maptype *map, prefix##_iter_t *iter) \
1398 prefix##_entry_t *rmv; \
1401 tor_assert(*iter); \
1403 iter = HT_NEXT_RMV(prefix##_impl, &map->head, iter); \
1404 prefix##_entry_free(rmv); \
1407 /** Set *<b>keyp</b> and *<b>valp</b> to the current entry pointed \
1410 prefix##_iter_get(prefix##_iter_t *iter, const keytype *keyp, \
1414 tor_assert(*iter); \
1417 *keyp = (*iter)->key; \
1418 *valp = (*iter)->val; \
1420 /** Return true iff <b>iter</b> has advanced past the last entry of \
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. */
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. */
1439 char *lc_key
= tor_strdup(key
);
1440 tor_strlower(lc_key
);
1441 v
= strmap_set(map
,lc_key
,val
);
1446 /** Same as strmap_get, but first converts <b>key</b> to lowercase. */
1448 strmap_get_lc(const strmap_t
*map
, const char *key
)
1451 char *lc_key
= tor_strdup(key
);
1452 tor_strlower(lc_key
);
1453 v
= strmap_get(map
,lc_key
);
1458 /** Same as strmap_remove, but first converts <b>key</b> to lowercase */
1460 strmap_remove_lc(strmap_t
*map
, const char *key
)
1463 char *lc_key
= tor_strdup(key
);
1464 tor_strlower(lc_key
);
1465 v
= strmap_remove(map
,lc_key
);
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) \
1478 _cmp_ ## elt_t(const void *_a, const void *_b) \
1480 const elt_t *a = _a, *b = _b; \
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. */
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
);
1526 /** Free all storage held in <b>set</b>. */
1528 digestset_free(digestset_t
*set
)
1532 bitarray_free(set
->ba
);