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 */
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.
34 smartlist_t
*sl
= tor_malloc(sizeof(smartlist_t
));
36 sl
->capacity
= SMARTLIST_DEFAULT_CAPACITY
;
37 sl
->list
= tor_malloc(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
)
61 /** Make sure that <b>sl</b> can hold at least <b>size</b> entries. */
63 smartlist_ensure_capacity(smartlist_t
*sl
, int size
)
65 #if SIZEOF_SIZE_T > SIZEOF_INT
66 #define MAX_CAPACITY (INT_MAX)
68 #define MAX_CAPACITY (int)((SIZE_MAX / (sizeof(void*))))
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
;
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. */
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. */
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
108 smartlist_remove(smartlist_t
*sl
, const void *element
)
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,
123 smartlist_pop_last(smartlist_t
*sl
)
127 return sl
->list
[--sl
->num_used
];
132 /** Reverse the order of the items in <b>sl</b>. */
134 smartlist_reverse(smartlist_t
*sl
)
139 for (i
= 0, j
= sl
->num_used
-1; i
< j
; ++i
, --j
) {
141 sl
->list
[i
] = sl
->list
[j
];
146 /** If there are any strings in sl equal to element, remove and free them.
147 * Does not preserve order. */
149 smartlist_string_remove(smartlist_t
*sl
, const char *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
)
169 for (i
=0; i
< sl
->num_used
; i
++)
170 if (sl
->list
[i
] == element
)
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
)
183 for (i
=0; i
< sl
->num_used
; i
++)
184 if (strcmp((const char*)sl
->list
[i
],element
)==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
)
196 for (i
=0; i
< sl
->num_used
; i
++)
197 if (strcmp((const char*)sl
->list
[i
],element
)==0)
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
)
210 for (i
=0; i
< sl
->num_used
; i
++)
211 if (strcasecmp((const char*)sl
->list
[i
],element
)==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
)
236 if (smartlist_len(sl1
) != smartlist_len(sl2
))
238 SMARTLIST_FOREACH(sl1
, const char *, cp1
, {
239 const char *cp2
= smartlist_get(sl2
, cp1_sl_idx
);
240 if (strcmp(cp1
, cp2
))
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
)
255 if (smartlist_len(sl1
) != smartlist_len(sl2
))
257 SMARTLIST_FOREACH(sl1
, int *, cp1
, {
258 int *cp2
= smartlist_get(sl2
, cp1_sl_idx
);
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
)
273 for (i
=0; i
< sl
->num_used
; i
++)
274 if (tor_memeq((const char*)sl
->list
[i
],element
,DIGEST_LEN
))
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
)
285 for (i
=0; i
< sl2
->num_used
; i
++)
286 if (smartlist_contains(sl1
, sl2
->list
[i
]))
291 /** Remove every element E of sl1 such that !smartlist_contains(sl2,E).
292 * Does not preserve the order of sl1.
295 smartlist_intersect(smartlist_t
*sl1
, const smartlist_t
*sl2
)
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.
309 smartlist_subtract(smartlist_t
*sl1
, const smartlist_t
*sl2
)
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.
320 smartlist_del(smartlist_t
*sl
, int idx
)
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.
333 smartlist_del_keeporder(smartlist_t
*sl
, int idx
)
337 tor_assert(idx
< 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
348 smartlist_insert(smartlist_t
*sl
, int idx
, void *val
)
352 tor_assert(idx
<= sl
->num_used
);
353 if (idx
== sl
->num_used
) {
354 smartlist_add(sl
, val
);
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
));
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>&SPLIT_SKIP_SPACE is true, remove initial and
372 * trailing space from each entry.
373 * If <b>flags</b>&SPLIT_IGNORE_BLANK is true, remove any entries
375 * If <b>flags</b>&SPLIT_STRIP_SPACE is true, strip spaces from each
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
,
385 const char *cp
, *end
, *next
;
393 if (flags
&SPLIT_SKIP_SPACE
) {
394 while (TOR_ISSPACE(*cp
)) ++cp
;
397 if (max
>0 && n
== max
-1) {
398 end
= strchr(cp
,'\0');
400 end
= strstr(cp
,sep
);
402 end
= strchr(cp
,'\0');
404 for (end
= cp
; *end
&& *end
!= '\t' && *end
!= ' '; ++end
)
413 next
= end
+strlen(sep
);
416 while (*next
== '\t' || *next
== ' ')
420 if (flags
&SPLIT_SKIP_SPACE
) {
421 while (end
> cp
&& TOR_ISSPACE(*(end
-1)))
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
);
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.
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
459 smartlist_join_strings2(smartlist_t
*sl
, const char *join
,
460 size_t join_len
, int terminate
, size_t *len_out
)
464 char *r
= NULL
, *dst
, *src
;
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 */
477 dst
= r
= tor_malloc(n
+1);
478 for (i
= 0; i
< sl
->num_used
; ) {
479 for (src
= sl
->list
[i
]; *src
; )
481 if (++i
< sl
->num_used
) {
482 memcpy(dst
, join
, join_len
);
487 memcpy(dst
, join
, join_len
);
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.
502 smartlist_sort(smartlist_t
*sl
, int (*compare
)(const void **a
, const void **b
))
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.
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
;
526 for (i
= 0; i
< sl
->num_used
; ++i
) {
527 const void *item
= sl
->list
[i
];
528 if (cur
&& 0 == compare(&cur
, &item
)) {
531 if (cur
&& count
>= most_frequent_count
) {
533 most_frequent_count
= count
;
539 if (cur
&& count
>= most_frequent_count
) {
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.
551 smartlist_uniq(smartlist_t
*sl
,
552 int (*compare
)(const void **a
, const void **b
),
553 void (*free_fn
)(void *a
))
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) {
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.
572 smartlist_bsearch(smartlist_t
*sl
, const void *key
,
573 int (*compare
)(const void *key
, const void **member
))
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
),
593 int hi
, lo
, cmp
, mid
, len
, diff
;
597 tor_assert(found_out
);
599 len
= smartlist_len(sl
);
601 /* Check for the trivial case of a zero-length list */
604 /* We already know smartlist_len(sl) is 0 in this case */
608 /* Okay, we have a real search to do */
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
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
]));
630 /* sl[mid] == key; we found it */
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] */
653 /* This should always be true in this case */
657 * key < sl[mid] and an index i such that sl[i] == key must
658 * have i < mid if it exists.
662 /* Normal case, move hi to the element immediately before sl[mid] */
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.
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 */
684 tor_assert(lo
<= len
);
686 tor_assert(hi
<= len
);
689 cmp
= compare(key
, (const void **) &(sl
->list
[lo
]));
692 cmp
= compare(key
, (const void **) &(sl
->list
[len
-1]));
700 /** Helper: compare two const char **s. */
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
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> */
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().
725 smartlist_uniq_strings(smartlist_t
*sl
)
727 smartlist_uniq(sl
, compare_string_ptrs_
, tor_free_
);
730 /** Helper: compare two pointers. */
732 compare_ptrs_(const void **_a
, const void **_b
)
734 const void *a
= *_a
, *b
= *_b
;
743 /** Sort <b>sl</b> in ascending order of the pointers it contains. */
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.
760 * typedef struct 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) {
769 * } else if (t1->tv.tv_sec > t2->tv.tv_sec) {
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),
781 * void timer_heap_pop(smartlist_t *heap) {
782 * return smartlist_pqueue_pop(heap, compare,
783 * STRUCT_OFFSET(timer_t, heap_index));
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 )
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; \
815 #define IDX_OF_ITEM(p) (*IDXP(p))
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. */
822 smartlist_heapify(smartlist_t
*sl
,
823 int (*compare
)(const void *a
, const void *b
),
824 int idx_field_offset
,
828 int left_idx
= LEFT_CHILD(idx
);
831 if (left_idx
>= sl
->num_used
)
833 if (compare(sl
->list
[idx
],sl
->list
[left_idx
]) < 0)
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
) {
844 void *tmp
= sl
->list
[idx
];
845 sl
->list
[idx
] = sl
->list
[best_idx
];
846 sl
->list
[best_idx
] = tmp
;
848 UPDATE_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
861 smartlist_pqueue_add(smartlist_t
*sl
,
862 int (*compare
)(const void *a
, const void *b
),
863 int idx_field_offset
,
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
];
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
890 smartlist_pqueue_pop(smartlist_t
*sl
,
891 int (*compare
)(const void *a
, const void *b
),
892 int idx_field_offset
)
895 tor_assert(sl
->num_used
);
899 if (--sl
->num_used
) {
900 sl
->list
[0] = sl
->list
[sl
->num_used
];
902 smartlist_heapify(sl
, compare
, idx_field_offset
, 0);
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
912 smartlist_pqueue_remove(smartlist_t
*sl
,
913 int (*compare
)(const void *a
, const void *b
),
914 int idx_field_offset
,
917 int idx
= IDX_OF_ITEM(item
);
918 tor_assert(idx
>= 0);
919 tor_assert(sl
->list
[idx
] == item
);
922 if (idx
== sl
->num_used
) {
925 sl
->list
[idx
] = sl
->list
[sl
->num_used
];
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>. */
934 smartlist_pqueue_assert_ok(smartlist_t
*sl
,
935 int (*compare
)(const void *a
, const void *b
),
936 int idx_field_offset
)
939 for (i
= sl
->num_used
- 1; i
>= 0; --i
) {
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. */
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. */
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().
963 smartlist_uniq_digests(smartlist_t
*sl
)
965 smartlist_uniq(sl
, compare_digests_
, tor_free_
);
968 /** Helper: compare two DIGEST256_LEN digests. */
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. */
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> */
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
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; \
1008 } prefix ## entry_t; \
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. */
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. */
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
,
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.
1060 result
= tor_malloc(sizeof(strmap_t
));
1061 HT_INIT(strmap_impl
, &result
->head
);
1065 /** Constructor to create a new empty map from digests to void*'s.
1070 digestmap_t
*result
;
1071 result
= tor_malloc(sizeof(digestmap_t
));
1072 HT_INIT(digestmap_impl
, &result
->head
);
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
1083 strmap_set(strmap_t
*map
, const char *key
, void *val
)
1085 strmap_entry_t
*resolve
;
1086 strmap_entry_t search
;
1091 search
.key
= (char*)key
;
1092 resolve
= HT_FIND(strmap_impl
, &map
->head
, &search
);
1094 oldval
= resolve
->val
;
1098 resolve
= tor_malloc_zero(sizeof(strmap_entry_t
));
1099 resolve
->key
= tor_strdup(key
);
1101 tor_assert(!HT_FIND(strmap_impl
, &map
->head
, resolve
));
1102 HT_INSERT(strmap_impl
, &map
->head
, resolve
);
1107 #define OPTIMIZED_DIGESTMAP_SET
1109 /** Like strmap_set() above but for digestmaps. */
1111 digestmap_set(digestmap_t
*map
, const char *key
, void *val
)
1113 #ifndef OPTIMIZED_DIGESTMAP_SET
1114 digestmap_entry_t
*resolve
;
1116 digestmap_entry_t search
;
1121 memcpy(&search
.key
, key
, DIGEST_LEN
);
1122 #ifndef OPTIMIZED_DIGESTMAP_SET
1123 resolve
= HT_FIND(digestmap_impl
, &map
->head
, &search
);
1125 oldval
= resolve
->val
;
1129 resolve
= tor_malloc_zero(sizeof(digestmap_entry_t
));
1130 memcpy(resolve
->key
, key
, DIGEST_LEN
);
1132 HT_INSERT(digestmap_impl
, &map
->head
, resolve
);
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
;
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
);
1155 HT_FOI_INSERT_(node
, &(map
->head
), &search
, newent
, ptr
);
1161 /** Return the current value associated with <b>key</b>, or NULL if no
1165 strmap_get(const strmap_t
*map
, const char *key
)
1167 strmap_entry_t
*resolve
;
1168 strmap_entry_t search
;
1171 search
.key
= (char*)key
;
1172 resolve
= HT_FIND(strmap_impl
, &map
->head
, &search
);
1174 return resolve
->val
;
1180 /** Like strmap_get() above but for digestmaps. */
1182 digestmap_get(const digestmap_t
*map
, const char *key
)
1184 digestmap_entry_t
*resolve
;
1185 digestmap_entry_t search
;
1188 memcpy(&search
.key
, key
, DIGEST_LEN
);
1189 resolve
= HT_FIND(digestmap_impl
, &map
->head
, &search
);
1191 return resolve
->val
;
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
1201 * Note: you must free any storage associated with the returned value.
1204 strmap_remove(strmap_t
*map
, const char *key
)
1206 strmap_entry_t
*resolve
;
1207 strmap_entry_t search
;
1211 search
.key
= (char*)key
;
1212 resolve
= HT_REMOVE(strmap_impl
, &map
->head
, &search
);
1214 oldval
= resolve
->val
;
1215 tor_free(resolve
->key
);
1223 /** Like strmap_remove() above but for digestmaps. */
1225 digestmap_remove(digestmap_t
*map
, const char *key
)
1227 digestmap_entry_t
*resolve
;
1228 digestmap_entry_t search
;
1232 memcpy(&search
.key
, key
, DIGEST_LEN
);
1233 resolve
= HT_REMOVE(digestmap_impl
, &map
->head
, &search
);
1235 oldval
= resolve
->val
;
1243 /** Same as strmap_set, but first converts <b>key</b> to lowercase. */
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. */
1250 char *lc_key
= tor_strdup(key
);
1251 tor_strlower(lc_key
);
1252 v
= strmap_set(map
,lc_key
,val
);
1257 /** Same as strmap_get, but first converts <b>key</b> to lowercase. */
1259 strmap_get_lc(const strmap_t
*map
, const char *key
)
1262 char *lc_key
= tor_strdup(key
);
1263 tor_strlower(lc_key
);
1264 v
= strmap_get(map
,lc_key
);
1269 /** Same as strmap_remove, but first converts <b>key</b> to lowercase */
1271 strmap_remove_lc(strmap_t
*map
, const char *key
)
1274 char *lc_key
= tor_strdup(key
);
1275 tor_strlower(lc_key
);
1276 v
= strmap_remove(map
,lc_key
);
1281 /** return an <b>iterator</b> pointer to the front of a map.
1286 * // uppercase values in "map", removing empty values.
1288 * strmap_iter_t *iter;
1293 * for (iter = strmap_iter_init(map); !strmap_iter_done(iter); ) {
1294 * strmap_iter_get(iter, &key, &val);
1297 * iter = strmap_iter_next_rmv(map,iter);
1300 * for (;*cp;cp++) *cp = TOR_TOUPPER(*cp);
1301 * iter = strmap_iter_next(map,iter);
1308 strmap_iter_init(strmap_t
*map
)
1311 return HT_START(strmap_impl
, &map
->head
);
1314 /** Start iterating through <b>map</b>. See strmap_iter_init() for example. */
1316 digestmap_iter_init(digestmap_t
*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. */
1325 strmap_iter_next(strmap_t
*map
, strmap_iter_t
*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. */
1335 digestmap_iter_next(digestmap_t
*map
, digestmap_iter_t
*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.
1346 strmap_iter_next_rmv(strmap_t
*map
, strmap_iter_t
*iter
)
1348 strmap_entry_t
*rmv
;
1353 iter
= HT_NEXT_RMV(strmap_impl
, &map
->head
, 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.
1363 digestmap_iter_next_rmv(digestmap_t
*map
, digestmap_iter_t
*iter
)
1365 digestmap_entry_t
*rmv
;
1370 iter
= HT_NEXT_RMV(digestmap_impl
, &map
->head
, iter
);
1375 /** Set *<b>keyp</b> and *<b>valp</b> to the current entry pointed to by
1378 strmap_iter_get(strmap_iter_t
*iter
, const char **keyp
, void **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
1391 digestmap_iter_get(digestmap_iter_t
*iter
, const char **keyp
, void **valp
)
1397 *keyp
= (*iter
)->key
;
1398 *valp
= (*iter
)->val
;
1401 /** Return true iff <b>iter</b> has advanced past the last entry of
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
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
1422 strmap_free(strmap_t
*map
, void (*free_val
)(void*))
1424 strmap_entry_t
**ent
, **next
, *this;
1428 for (ent
= HT_START(strmap_impl
, &map
->head
); ent
!= NULL
; ent
= next
) {
1430 next
= HT_NEXT_RMV(strmap_impl
, &map
->head
, ent
);
1431 tor_free(this->key
);
1433 free_val(this->val
);
1436 tor_assert(HT_EMPTY(&map
->head
));
1437 HT_CLEAR(strmap_impl
, &map
->head
);
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
1446 digestmap_free(digestmap_t
*map
, void (*free_val
)(void*))
1448 digestmap_entry_t
**ent
, **next
, *this;
1451 for (ent
= HT_START(digestmap_impl
, &map
->head
); ent
!= NULL
; ent
= next
) {
1453 next
= HT_NEXT_RMV(digestmap_impl
, &map
->head
, ent
);
1455 free_val(this->val
);
1458 tor_assert(HT_EMPTY(&map
->head
));
1459 HT_CLEAR(digestmap_impl
, &map
->head
);
1463 /** Fail with an assertion error if anything has gone wrong with the internal
1464 * representation of <b>map</b>. */
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>. */
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) \
1514 _cmp_ ## elt_t(const void *_a, const void *_b) \
1516 const elt_t *a = _a, *b = _b; \
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. */
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
);
1562 /** Free all storage held in <b>set</b>. */
1564 digestset_free(digestset_t
*set
)
1568 bitarray_free(set
->ba
);