1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2010, 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.
32 smartlist_create(void)
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 (size
> sl
->capacity
) {
66 int higher
= sl
->capacity
* 2;
69 tor_assert(higher
> 0); /* detect overflow */
70 sl
->capacity
= higher
;
71 sl
->list
= tor_realloc(sl
->list
, sizeof(void*)*sl
->capacity
);
75 /** Append element to the end of the list. */
77 smartlist_add(smartlist_t
*sl
, void *element
)
79 smartlist_ensure_capacity(sl
, sl
->num_used
+1);
80 sl
->list
[sl
->num_used
++] = element
;
83 /** Append each element from S2 to the end of S1. */
85 smartlist_add_all(smartlist_t
*s1
, const smartlist_t
*s2
)
87 int new_size
= s1
->num_used
+ s2
->num_used
;
88 tor_assert(new_size
>= s1
->num_used
); /* check for overflow. */
89 smartlist_ensure_capacity(s1
, new_size
);
90 memcpy(s1
->list
+ s1
->num_used
, s2
->list
, s2
->num_used
*sizeof(void*));
91 s1
->num_used
= new_size
;
94 /** Remove all elements E from sl such that E==element. Preserve
95 * the order of any elements before E, but elements after E can be
99 smartlist_remove(smartlist_t
*sl
, const void *element
)
104 for (i
=0; i
< sl
->num_used
; i
++)
105 if (sl
->list
[i
] == element
) {
106 sl
->list
[i
] = sl
->list
[--sl
->num_used
]; /* swap with the end */
107 i
--; /* so we process the new i'th element */
111 /** If <b>sl</b> is nonempty, remove and return the final element. Otherwise,
114 smartlist_pop_last(smartlist_t
*sl
)
118 return sl
->list
[--sl
->num_used
];
123 /** Reverse the order of the items in <b>sl</b>. */
125 smartlist_reverse(smartlist_t
*sl
)
130 for (i
= 0, j
= sl
->num_used
-1; i
< j
; ++i
, --j
) {
132 sl
->list
[i
] = sl
->list
[j
];
137 /** If there are any strings in sl equal to element, remove and free them.
138 * Does not preserve order. */
140 smartlist_string_remove(smartlist_t
*sl
, const char *element
)
145 for (i
= 0; i
< sl
->num_used
; ++i
) {
146 if (!strcmp(element
, sl
->list
[i
])) {
147 tor_free(sl
->list
[i
]);
148 sl
->list
[i
] = sl
->list
[--sl
->num_used
]; /* swap with the end */
149 i
--; /* so we process the new i'th element */
154 /** Return true iff some element E of sl has E==element.
157 smartlist_isin(const smartlist_t
*sl
, const void *element
)
160 for (i
=0; i
< sl
->num_used
; i
++)
161 if (sl
->list
[i
] == element
)
166 /** Return true iff <b>sl</b> has some element E such that
167 * !strcmp(E,<b>element</b>)
170 smartlist_string_isin(const smartlist_t
*sl
, const char *element
)
174 for (i
=0; i
< sl
->num_used
; i
++)
175 if (strcmp((const char*)sl
->list
[i
],element
)==0)
180 /** If <b>element</b> is equal to an element of <b>sl</b>, return that
181 * element's index. Otherwise, return -1. */
183 smartlist_string_pos(const smartlist_t
*sl
, const char *element
)
187 for (i
=0; i
< sl
->num_used
; i
++)
188 if (strcmp((const char*)sl
->list
[i
],element
)==0)
193 /** Return true iff <b>sl</b> has some element E such that
194 * !strcasecmp(E,<b>element</b>)
197 smartlist_string_isin_case(const smartlist_t
*sl
, const char *element
)
201 for (i
=0; i
< sl
->num_used
; i
++)
202 if (strcasecmp((const char*)sl
->list
[i
],element
)==0)
207 /** Return true iff <b>sl</b> has some element E such that E is equal
208 * to the decimal encoding of <b>num</b>.
211 smartlist_string_num_isin(const smartlist_t
*sl
, int num
)
214 tor_snprintf(buf
,sizeof(buf
),"%d", num
);
215 return smartlist_string_isin(sl
, buf
);
218 /** Return true iff <b>sl</b> has some element E such that
219 * !memcmp(E,<b>element</b>,DIGEST_LEN)
222 smartlist_digest_isin(const smartlist_t
*sl
, const char *element
)
226 for (i
=0; i
< sl
->num_used
; i
++)
227 if (memcmp((const char*)sl
->list
[i
],element
,DIGEST_LEN
)==0)
232 /** Return true iff some element E of sl2 has smartlist_isin(sl1,E).
235 smartlist_overlap(const smartlist_t
*sl1
, const smartlist_t
*sl2
)
238 for (i
=0; i
< sl2
->num_used
; i
++)
239 if (smartlist_isin(sl1
, sl2
->list
[i
]))
244 /** Remove every element E of sl1 such that !smartlist_isin(sl2,E).
245 * Does not preserve the order of sl1.
248 smartlist_intersect(smartlist_t
*sl1
, const smartlist_t
*sl2
)
251 for (i
=0; i
< sl1
->num_used
; i
++)
252 if (!smartlist_isin(sl2
, sl1
->list
[i
])) {
253 sl1
->list
[i
] = sl1
->list
[--sl1
->num_used
]; /* swap with the end */
254 i
--; /* so we process the new i'th element */
258 /** Remove every element E of sl1 such that smartlist_isin(sl2,E).
259 * Does not preserve the order of sl1.
262 smartlist_subtract(smartlist_t
*sl1
, const smartlist_t
*sl2
)
265 for (i
=0; i
< sl2
->num_used
; i
++)
266 smartlist_remove(sl1
, sl2
->list
[i
]);
269 /** Remove the <b>idx</b>th element of sl; if idx is not the last
270 * element, swap the last element of sl into the <b>idx</b>th space.
271 * Return the old value of the <b>idx</b>th element.
274 smartlist_del(smartlist_t
*sl
, int idx
)
278 tor_assert(idx
< sl
->num_used
);
279 sl
->list
[idx
] = sl
->list
[--sl
->num_used
];
282 /** Remove the <b>idx</b>th element of sl; if idx is not the last element,
283 * moving all subsequent elements back one space. Return the old value
284 * of the <b>idx</b>th element.
287 smartlist_del_keeporder(smartlist_t
*sl
, int idx
)
291 tor_assert(idx
< sl
->num_used
);
293 if (idx
< sl
->num_used
)
294 memmove(sl
->list
+idx
, sl
->list
+idx
+1, sizeof(void*)*(sl
->num_used
-idx
));
297 /** Insert the value <b>val</b> as the new <b>idx</b>th element of
298 * <b>sl</b>, moving all items previously at <b>idx</b> or later
302 smartlist_insert(smartlist_t
*sl
, int idx
, void *val
)
306 tor_assert(idx
<= sl
->num_used
);
307 if (idx
== sl
->num_used
) {
308 smartlist_add(sl
, val
);
310 smartlist_ensure_capacity(sl
, sl
->num_used
+1);
311 /* Move other elements away */
312 if (idx
< sl
->num_used
)
313 memmove(sl
->list
+ idx
+ 1, sl
->list
+ idx
,
314 sizeof(void*)*(sl
->num_used
-idx
));
321 * Split a string <b>str</b> along all occurrences of <b>sep</b>,
322 * adding the split strings, in order, to <b>sl</b>.
324 * If <b>flags</b>&SPLIT_SKIP_SPACE is true, remove initial and
325 * trailing space from each entry.
326 * If <b>flags</b>&SPLIT_IGNORE_BLANK is true, remove any entries
328 * If <b>flags</b>&SPLIT_STRIP_SPACE is true, strip spaces from each
331 * If max>0, divide the string into no more than <b>max</b> pieces. If
332 * <b>sep</b> is NULL, split on any sequence of horizontal space.
335 smartlist_split_string(smartlist_t
*sl
, const char *str
, const char *sep
,
338 const char *cp
, *end
, *next
;
346 if (flags
&SPLIT_SKIP_SPACE
) {
347 while (TOR_ISSPACE(*cp
)) ++cp
;
350 if (max
>0 && n
== max
-1) {
351 end
= strchr(cp
,'\0');
353 end
= strstr(cp
,sep
);
355 end
= strchr(cp
,'\0');
357 for (end
= cp
; *end
&& *end
!= '\t' && *end
!= ' '; ++end
)
366 next
= end
+strlen(sep
);
369 while (*next
== '\t' || *next
== ' ')
373 if (flags
&SPLIT_SKIP_SPACE
) {
374 while (end
> cp
&& TOR_ISSPACE(*(end
-1)))
377 if (end
!= cp
|| !(flags
&SPLIT_IGNORE_BLANK
)) {
378 char *string
= tor_strndup(cp
, end
-cp
);
379 if (flags
&SPLIT_STRIP_SPACE
)
380 tor_strstrip(string
, " ");
381 smartlist_add(sl
, string
);
392 /** Allocate and return a new string containing the concatenation of
393 * the elements of <b>sl</b>, in order, separated by <b>join</b>. If
394 * <b>terminate</b> is true, also terminate the string with <b>join</b>.
395 * If <b>len_out</b> is not NULL, set <b>len_out</b> to the length of
396 * the returned string. Requires that every element of <b>sl</b> is
397 * NUL-terminated string.
400 smartlist_join_strings(smartlist_t
*sl
, const char *join
,
401 int terminate
, size_t *len_out
)
403 return smartlist_join_strings2(sl
,join
,strlen(join
),terminate
,len_out
);
406 /** As smartlist_join_strings, but instead of separating/terminated with a
407 * NUL-terminated string <b>join</b>, uses the <b>join_len</b>-byte sequence
408 * at <b>join</b>. (Useful for generating a sequence of NUL-terminated
412 smartlist_join_strings2(smartlist_t
*sl
, const char *join
,
413 size_t join_len
, int terminate
, size_t *len_out
)
417 char *r
= NULL
, *dst
, *src
;
425 for (i
= 0; i
< sl
->num_used
; ++i
) {
426 n
+= strlen(sl
->list
[i
]);
427 if (i
+1 < sl
->num_used
) /* avoid double-counting the last one */
430 dst
= r
= tor_malloc(n
+1);
431 for (i
= 0; i
< sl
->num_used
; ) {
432 for (src
= sl
->list
[i
]; *src
; )
434 if (++i
< sl
->num_used
) {
435 memcpy(dst
, join
, join_len
);
440 memcpy(dst
, join
, join_len
);
450 /** Sort the members of <b>sl</b> into an order defined by
451 * the ordering function <b>compare</b>, which returns less then 0 if a
452 * precedes b, greater than 0 if b precedes a, and 0 if a 'equals' b.
455 smartlist_sort(smartlist_t
*sl
, int (*compare
)(const void **a
, const void **b
))
459 qsort(sl
->list
, sl
->num_used
, sizeof(void*),
460 (int (*)(const void *,const void*))compare
);
463 /** Given a smartlist <b>sl</b> sorted with the function <b>compare</b>,
464 * return the most frequent member in the list. Break ties in favor of
465 * later elements. If the list is empty, return NULL.
468 smartlist_get_most_frequent(const smartlist_t
*sl
,
469 int (*compare
)(const void **a
, const void **b
))
471 const void *most_frequent
= NULL
;
472 int most_frequent_count
= 0;
474 const void *cur
= NULL
;
479 for (i
= 0; i
< sl
->num_used
; ++i
) {
480 const void *item
= sl
->list
[i
];
481 if (cur
&& 0 == compare(&cur
, &item
)) {
484 if (cur
&& count
>= most_frequent_count
) {
486 most_frequent_count
= count
;
492 if (cur
&& count
>= most_frequent_count
) {
494 most_frequent_count
= count
;
496 return (void*)most_frequent
;
499 /** Given a sorted smartlist <b>sl</b> and the comparison function used to
500 * sort it, remove all duplicate members. If free_fn is provided, calls
501 * free_fn on each duplicate. Otherwise, just removes them. Preserves order.
504 smartlist_uniq(smartlist_t
*sl
,
505 int (*compare
)(const void **a
, const void **b
),
506 void (*free_fn
)(void *a
))
509 for (i
=1; i
< sl
->num_used
; ++i
) {
510 if (compare((const void **)&(sl
->list
[i
-1]),
511 (const void **)&(sl
->list
[i
])) == 0) {
513 free_fn(sl
->list
[i
]);
514 smartlist_del_keeporder(sl
, i
--);
519 /** Assuming the members of <b>sl</b> are in order, return a pointer to the
520 * member that matches <b>key</b>. Ordering and matching are defined by a
521 * <b>compare</b> function that returns 0 on a match; less than 0 if key is
522 * less than member, and greater than 0 if key is greater then member.
525 smartlist_bsearch(smartlist_t
*sl
, const void *key
,
526 int (*compare
)(const void *key
, const void **member
))
529 idx
= smartlist_bsearch_idx(sl
, key
, compare
, &found
);
530 return found
? smartlist_get(sl
, idx
) : NULL
;
533 /** Assuming the members of <b>sl</b> are in order, return the index of the
534 * member that matches <b>key</b>. If no member matches, return the index of
535 * the first member greater than <b>key</b>, or smartlist_len(sl) if no member
536 * is greater than <b>key</b>. Set <b>found_out</b> to true on a match, to
537 * false otherwise. Ordering and matching are defined by a <b>compare</b>
538 * function that returns 0 on a match; less than 0 if key is less than member,
539 * and greater than 0 if key is greater then member.
542 smartlist_bsearch_idx(const smartlist_t
*sl
, const void *key
,
543 int (*compare
)(const void *key
, const void **member
),
546 int hi
= smartlist_len(sl
) - 1, lo
= 0, cmp
, mid
;
550 cmp
= compare(key
, (const void**) &(sl
->list
[mid
]));
551 if (cmp
>0) { /* key > sl[mid] */
553 } else if (cmp
<0) { /* key < sl[mid] */
555 } else { /* key == sl[mid] */
563 if (lo
< smartlist_len(sl
)) {
564 cmp
= compare(key
, (const void**) &(sl
->list
[lo
]));
566 } else if (smartlist_len(sl
)) {
567 cmp
= compare(key
, (const void**) &(sl
->list
[smartlist_len(sl
)-1]));
575 /** Helper: compare two const char **s. */
577 _compare_string_ptrs(const void **_a
, const void **_b
)
579 return strcmp((const char*)*_a
, (const char*)*_b
);
582 /** Sort a smartlist <b>sl</b> containing strings into lexically ascending
585 smartlist_sort_strings(smartlist_t
*sl
)
587 smartlist_sort(sl
, _compare_string_ptrs
);
590 /** Return the most frequent string in the sorted list <b>sl</b> */
592 smartlist_get_most_frequent_string(smartlist_t
*sl
)
594 return smartlist_get_most_frequent(sl
, _compare_string_ptrs
);
597 /** Remove duplicate strings from a sorted list, and free them with tor_free().
600 smartlist_uniq_strings(smartlist_t
*sl
)
602 smartlist_uniq(sl
, _compare_string_ptrs
, _tor_free
);
605 /* Heap-based priority queue implementation for O(lg N) insert and remove.
606 * Recall that the heap property is that, for every index I, h[I] <
607 * H[LEFT_CHILD[I]] and h[I] < H[RIGHT_CHILD[I]].
609 * For us to remove items other than the topmost item, each item must store
610 * its own index within the heap. When calling the pqueue functions, tell
611 * them about the offset of the field that stores the index within the item.
615 * typedef struct timer_t {
620 * static int compare(const void *p1, const void *p2) {
621 * const timer_t *t1 = p1, *t2 = p2;
622 * if (t1->tv.tv_sec < t2->tv.tv_sec) {
624 * } else if (t1->tv.tv_sec > t2->tv.tv_sec) {
627 * return t1->tv.tv_usec - t2->tv_usec;
631 * void timer_heap_insert(smartlist_t *heap, timer_t *timer) {
632 * smartlist_pqueue_add(heap, compare, STRUCT_OFFSET(timer_t, heap_index),
636 * void timer_heap_pop(smartlist_t *heap) {
637 * return smartlist_pqueue_pop(heap, compare,
638 * STRUCT_OFFSET(timer_t, heap_index));
642 /* For a 1-indexed array, we would use LEFT_CHILD[x] = 2*x and RIGHT_CHILD[x]
643 * = 2*x + 1. But this is C, so we have to adjust a little. */
644 //#define LEFT_CHILD(i) ( ((i)+1)*2 - 1)
645 //#define RIGHT_CHILD(i) ( ((i)+1)*2 )
646 //#define PARENT(i) ( ((i)+1)/2 - 1)
647 #define LEFT_CHILD(i) ( 2*(i) + 1 )
648 #define RIGHT_CHILD(i) ( 2*(i) + 2 )
649 #define PARENT(i) ( ((i)-1) / 2 )
651 #define IDXP(p) ((int*)STRUCT_VAR_P(p, idx_field_offset))
653 #define UPDATE_IDX(i) do { \
654 void *updated = sl->list[i]; \
655 *IDXP(updated) = i; \
658 #define IDX_OF_ITEM(p) (*IDXP(p))
660 /** Helper. <b>sl</b> may have at most one violation of the heap property:
661 * the item at <b>idx</b> may be greater than one or both of its children.
662 * Restore the heap property. */
664 smartlist_heapify(smartlist_t
*sl
,
665 int (*compare
)(const void *a
, const void *b
),
666 int idx_field_offset
,
670 int left_idx
= LEFT_CHILD(idx
);
673 if (left_idx
>= sl
->num_used
)
675 if (compare(sl
->list
[idx
],sl
->list
[left_idx
]) < 0)
679 if (left_idx
+1 < sl
->num_used
&&
680 compare(sl
->list
[left_idx
+1],sl
->list
[best_idx
]) < 0)
681 best_idx
= left_idx
+ 1;
683 if (best_idx
== idx
) {
686 void *tmp
= sl
->list
[idx
];
687 sl
->list
[idx
] = sl
->list
[best_idx
];
688 sl
->list
[best_idx
] = tmp
;
690 UPDATE_IDX(best_idx
);
697 /** Insert <b>item</b> into the heap stored in <b>sl</b>, where order is
698 * determined by <b>compare</b> and the offset of the item in the heap is
699 * stored in an int-typed field at position <b>idx_field_offset</b> within
703 smartlist_pqueue_add(smartlist_t
*sl
,
704 int (*compare
)(const void *a
, const void *b
),
705 int idx_field_offset
,
709 smartlist_add(sl
,item
);
710 UPDATE_IDX(sl
->num_used
-1);
712 for (idx
= sl
->num_used
- 1; idx
; ) {
713 int parent
= PARENT(idx
);
714 if (compare(sl
->list
[idx
], sl
->list
[parent
]) < 0) {
715 void *tmp
= sl
->list
[parent
];
716 sl
->list
[parent
] = sl
->list
[idx
];
727 /** Remove and return the top-priority item from the heap stored in <b>sl</b>,
728 * where order is determined by <b>compare</b> and the item's position is
729 * stored at position <b>idx_field_offset</b> within the item. <b>sl</b> must
732 smartlist_pqueue_pop(smartlist_t
*sl
,
733 int (*compare
)(const void *a
, const void *b
),
734 int idx_field_offset
)
737 tor_assert(sl
->num_used
);
741 if (--sl
->num_used
) {
742 sl
->list
[0] = sl
->list
[sl
->num_used
];
744 smartlist_heapify(sl
, compare
, idx_field_offset
, 0);
749 /** Remove the item <b>item</b> from the heap stored in <b>sl</b>,
750 * where order is determined by <b>compare</b> and the item's position is
751 * stored at position <b>idx_field_offset</b> within the item. <b>sl</b> must
754 smartlist_pqueue_remove(smartlist_t
*sl
,
755 int (*compare
)(const void *a
, const void *b
),
756 int idx_field_offset
,
759 int idx
= IDX_OF_ITEM(item
);
760 tor_assert(idx
>= 0);
761 tor_assert(sl
->list
[idx
] == item
);
764 if (idx
== sl
->num_used
) {
767 sl
->list
[idx
] = sl
->list
[sl
->num_used
];
769 smartlist_heapify(sl
, compare
, idx_field_offset
, idx
);
773 /** Assert that the heap property is correctly maintained by the heap stored
774 * in <b>sl</b>, where order is determined by <b>compare</b>. */
776 smartlist_pqueue_assert_ok(smartlist_t
*sl
,
777 int (*compare
)(const void *a
, const void *b
),
778 int idx_field_offset
)
781 for (i
= sl
->num_used
- 1; i
>= 0; --i
) {
783 tor_assert(compare(sl
->list
[PARENT(i
)], sl
->list
[i
]) <= 0);
784 tor_assert(IDX_OF_ITEM(sl
->list
[i
]) == i
);
788 /** Helper: compare two DIGEST_LEN digests. */
790 _compare_digests(const void **_a
, const void **_b
)
792 return memcmp((const char*)*_a
, (const char*)*_b
, DIGEST_LEN
);
795 /** Sort the list of DIGEST_LEN-byte digests into ascending order. */
797 smartlist_sort_digests(smartlist_t
*sl
)
799 smartlist_sort(sl
, _compare_digests
);
802 /** Remove duplicate digests from a sorted list, and free them with tor_free().
805 smartlist_uniq_digests(smartlist_t
*sl
)
807 smartlist_uniq(sl
, _compare_digests
, _tor_free
);
810 /** Helper: compare two DIGEST256_LEN digests. */
812 _compare_digests256(const void **_a
, const void **_b
)
814 return memcmp((const char*)*_a
, (const char*)*_b
, DIGEST256_LEN
);
817 /** Sort the list of DIGEST256_LEN-byte digests into ascending order. */
819 smartlist_sort_digests256(smartlist_t
*sl
)
821 smartlist_sort(sl
, _compare_digests256
);
824 /** Return the most frequent member of the sorted list of DIGEST256_LEN
825 * digests in <b>sl</b> */
827 smartlist_get_most_frequent_digest256(smartlist_t
*sl
)
829 return smartlist_get_most_frequent(sl
, _compare_digests256
);
832 /** Remove duplicate 256-bit digests from a sorted list, and free them with
836 smartlist_uniq_digests256(smartlist_t
*sl
)
838 smartlist_uniq(sl
, _compare_digests256
, _tor_free
);
841 /** Helper: Declare an entry type and a map type to implement a mapping using
842 * ht.h. The map type will be called <b>maptype</b>. The key part of each
843 * entry is declared using the C declaration <b>keydecl</b>. All functions
844 * and types associated with the map get prefixed with <b>prefix</b> */
845 #define DEFINE_MAP_STRUCTS(maptype, keydecl, prefix) \
846 typedef struct prefix ## entry_t { \
847 HT_ENTRY(prefix ## entry_t) node; \
850 } prefix ## entry_t; \
852 HT_HEAD(prefix ## impl, prefix ## entry_t) head; \
855 DEFINE_MAP_STRUCTS(strmap_t
, char *key
, strmap_
);
856 DEFINE_MAP_STRUCTS(digestmap_t
, char key
[DIGEST_LEN
], digestmap_
);
858 /** Helper: compare strmap_entry_t objects by key value. */
860 strmap_entries_eq(const strmap_entry_t
*a
, const strmap_entry_t
*b
)
862 return !strcmp(a
->key
, b
->key
);
865 /** Helper: return a hash value for a strmap_entry_t. */
866 static INLINE
unsigned int
867 strmap_entry_hash(const strmap_entry_t
*a
)
869 return ht_string_hash(a
->key
);
872 /** Helper: compare digestmap_entry_t objects by key value. */
874 digestmap_entries_eq(const digestmap_entry_t
*a
, const digestmap_entry_t
*b
)
876 return !memcmp(a
->key
, b
->key
, DIGEST_LEN
);
879 /** Helper: return a hash value for a digest_map_t. */
880 static INLINE
unsigned int
881 digestmap_entry_hash(const digestmap_entry_t
*a
)
884 const uint32_t *p
= (const uint32_t*)a
->key
;
885 return p
[0] ^ p
[1] ^ p
[2] ^ p
[3] ^ p
[4];
887 const uint64_t *p
= (const uint64_t*)a
->key
;
892 HT_PROTOTYPE(strmap_impl
, strmap_entry_t
, node
, strmap_entry_hash
,
894 HT_GENERATE(strmap_impl
, strmap_entry_t
, node
, strmap_entry_hash
,
895 strmap_entries_eq
, 0.6, malloc
, realloc
, free
)
897 HT_PROTOTYPE(digestmap_impl
, digestmap_entry_t
, node
, digestmap_entry_hash
,
898 digestmap_entries_eq
)
899 HT_GENERATE(digestmap_impl
, digestmap_entry_t
, node
, digestmap_entry_hash
,
900 digestmap_entries_eq
, 0.6, malloc
, realloc
, free
)
902 /** Constructor to create a new empty map from strings to void*'s.
908 result
= tor_malloc(sizeof(strmap_t
));
909 HT_INIT(strmap_impl
, &result
->head
);
913 /** Constructor to create a new empty map from digests to void*'s.
919 result
= tor_malloc(sizeof(digestmap_t
));
920 HT_INIT(digestmap_impl
, &result
->head
);
924 /** Set the current value for <b>key</b> to <b>val</b>. Returns the previous
925 * value for <b>key</b> if one was set, or NULL if one was not.
927 * This function makes a copy of <b>key</b> if necessary, but not of
931 strmap_set(strmap_t
*map
, const char *key
, void *val
)
933 strmap_entry_t
*resolve
;
934 strmap_entry_t search
;
939 search
.key
= (char*)key
;
940 resolve
= HT_FIND(strmap_impl
, &map
->head
, &search
);
942 oldval
= resolve
->val
;
946 resolve
= tor_malloc_zero(sizeof(strmap_entry_t
));
947 resolve
->key
= tor_strdup(key
);
949 tor_assert(!HT_FIND(strmap_impl
, &map
->head
, resolve
));
950 HT_INSERT(strmap_impl
, &map
->head
, resolve
);
955 #define OPTIMIZED_DIGESTMAP_SET
957 /** Like strmap_set() above but for digestmaps. */
959 digestmap_set(digestmap_t
*map
, const char *key
, void *val
)
961 #ifndef OPTIMIZED_DIGESTMAP_SET
962 digestmap_entry_t
*resolve
;
964 digestmap_entry_t search
;
969 memcpy(&search
.key
, key
, DIGEST_LEN
);
970 #ifndef OPTIMIZED_DIGESTMAP_SET
971 resolve
= HT_FIND(digestmap_impl
, &map
->head
, &search
);
973 oldval
= resolve
->val
;
977 resolve
= tor_malloc_zero(sizeof(digestmap_entry_t
));
978 memcpy(resolve
->key
, key
, DIGEST_LEN
);
980 HT_INSERT(digestmap_impl
, &map
->head
, resolve
);
984 /* We spend up to 5% of our time in this function, so the code below is
985 * meant to optimize the check/alloc/set cycle by avoiding the two trips to
986 * the hash table that we do in the unoptimized code above. (Each of
987 * HT_INSERT and HT_FIND calls HT_SET_HASH and HT_FIND_P.)
989 _HT_FIND_OR_INSERT(digestmap_impl
, node
, digestmap_entry_hash
, &(map
->head
),
990 digestmap_entry_t
, &search
, ptr
,
992 /* we found an entry. */
993 oldval
= (*ptr
)->val
;
998 /* We didn't find the entry. */
999 digestmap_entry_t
*newent
=
1000 tor_malloc_zero(sizeof(digestmap_entry_t
));
1001 memcpy(newent
->key
, key
, DIGEST_LEN
);
1003 _HT_FOI_INSERT(node
, &(map
->head
), &search
, newent
, ptr
);
1009 /** Return the current value associated with <b>key</b>, or NULL if no
1013 strmap_get(const strmap_t
*map
, const char *key
)
1015 strmap_entry_t
*resolve
;
1016 strmap_entry_t search
;
1019 search
.key
= (char*)key
;
1020 resolve
= HT_FIND(strmap_impl
, &map
->head
, &search
);
1022 return resolve
->val
;
1028 /** Like strmap_get() above but for digestmaps. */
1030 digestmap_get(const digestmap_t
*map
, const char *key
)
1032 digestmap_entry_t
*resolve
;
1033 digestmap_entry_t search
;
1036 memcpy(&search
.key
, key
, DIGEST_LEN
);
1037 resolve
= HT_FIND(digestmap_impl
, &map
->head
, &search
);
1039 return resolve
->val
;
1045 /** Remove the value currently associated with <b>key</b> from the map.
1046 * Return the value if one was set, or NULL if there was no entry for
1049 * Note: you must free any storage associated with the returned value.
1052 strmap_remove(strmap_t
*map
, const char *key
)
1054 strmap_entry_t
*resolve
;
1055 strmap_entry_t search
;
1059 search
.key
= (char*)key
;
1060 resolve
= HT_REMOVE(strmap_impl
, &map
->head
, &search
);
1062 oldval
= resolve
->val
;
1063 tor_free(resolve
->key
);
1071 /** Like strmap_remove() above but for digestmaps. */
1073 digestmap_remove(digestmap_t
*map
, const char *key
)
1075 digestmap_entry_t
*resolve
;
1076 digestmap_entry_t search
;
1080 memcpy(&search
.key
, key
, DIGEST_LEN
);
1081 resolve
= HT_REMOVE(digestmap_impl
, &map
->head
, &search
);
1083 oldval
= resolve
->val
;
1091 /** Same as strmap_set, but first converts <b>key</b> to lowercase. */
1093 strmap_set_lc(strmap_t
*map
, const char *key
, void *val
)
1095 /* We could be a little faster by using strcasecmp instead, and a separate
1096 * type, but I don't think it matters. */
1098 char *lc_key
= tor_strdup(key
);
1099 tor_strlower(lc_key
);
1100 v
= strmap_set(map
,lc_key
,val
);
1105 /** Same as strmap_get, but first converts <b>key</b> to lowercase. */
1107 strmap_get_lc(const strmap_t
*map
, const char *key
)
1110 char *lc_key
= tor_strdup(key
);
1111 tor_strlower(lc_key
);
1112 v
= strmap_get(map
,lc_key
);
1117 /** Same as strmap_remove, but first converts <b>key</b> to lowercase */
1119 strmap_remove_lc(strmap_t
*map
, const char *key
)
1122 char *lc_key
= tor_strdup(key
);
1123 tor_strlower(lc_key
);
1124 v
= strmap_remove(map
,lc_key
);
1129 /** return an <b>iterator</b> pointer to the front of a map.
1134 * // uppercase values in "map", removing empty values.
1136 * strmap_iter_t *iter;
1141 * for (iter = strmap_iter_init(map); !strmap_iter_done(iter); ) {
1142 * strmap_iter_get(iter, &key, &val);
1145 * iter = strmap_iter_next_rmv(map,iter);
1148 * for (;*cp;cp++) *cp = TOR_TOUPPER(*cp);
1149 * iter = strmap_iter_next(map,iter);
1156 strmap_iter_init(strmap_t
*map
)
1159 return HT_START(strmap_impl
, &map
->head
);
1162 /** Start iterating through <b>map</b>. See strmap_iter_init() for example. */
1164 digestmap_iter_init(digestmap_t
*map
)
1167 return HT_START(digestmap_impl
, &map
->head
);
1170 /** Advance the iterator <b>iter</b> for <b>map</b> a single step to the next
1171 * entry, and return its new value. */
1173 strmap_iter_next(strmap_t
*map
, strmap_iter_t
*iter
)
1177 return HT_NEXT(strmap_impl
, &map
->head
, iter
);
1180 /** Advance the iterator <b>iter</b> for map a single step to the next entry,
1181 * and return its new value. */
1183 digestmap_iter_next(digestmap_t
*map
, digestmap_iter_t
*iter
)
1187 return HT_NEXT(digestmap_impl
, &map
->head
, iter
);
1190 /** Advance the iterator <b>iter</b> a single step to the next entry, removing
1191 * the current entry, and return its new value.
1194 strmap_iter_next_rmv(strmap_t
*map
, strmap_iter_t
*iter
)
1196 strmap_entry_t
*rmv
;
1201 iter
= HT_NEXT_RMV(strmap_impl
, &map
->head
, iter
);
1207 /** Advance the iterator <b>iter</b> a single step to the next entry, removing
1208 * the current entry, and return its new value.
1211 digestmap_iter_next_rmv(digestmap_t
*map
, digestmap_iter_t
*iter
)
1213 digestmap_entry_t
*rmv
;
1218 iter
= HT_NEXT_RMV(digestmap_impl
, &map
->head
, iter
);
1223 /** Set *<b>keyp</b> and *<b>valp</b> to the current entry pointed to by
1226 strmap_iter_get(strmap_iter_t
*iter
, const char **keyp
, void **valp
)
1232 *keyp
= (*iter
)->key
;
1233 *valp
= (*iter
)->val
;
1236 /** Set *<b>keyp</b> and *<b>valp</b> to the current entry pointed to by
1239 digestmap_iter_get(digestmap_iter_t
*iter
, const char **keyp
, void **valp
)
1245 *keyp
= (*iter
)->key
;
1246 *valp
= (*iter
)->val
;
1249 /** Return true iff <b>iter</b> has advanced past the last entry of
1252 strmap_iter_done(strmap_iter_t
*iter
)
1254 return iter
== NULL
;
1257 /** Return true iff <b>iter</b> has advanced past the last entry of
1260 digestmap_iter_done(digestmap_iter_t
*iter
)
1262 return iter
== NULL
;
1265 /** Remove all entries from <b>map</b>, and deallocate storage for those
1266 * entries. If free_val is provided, it is invoked on every value in
1270 strmap_free(strmap_t
*map
, void (*free_val
)(void*))
1272 strmap_entry_t
**ent
, **next
, *this;
1276 for (ent
= HT_START(strmap_impl
, &map
->head
); ent
!= NULL
; ent
= next
) {
1278 next
= HT_NEXT_RMV(strmap_impl
, &map
->head
, ent
);
1279 tor_free(this->key
);
1281 free_val(this->val
);
1284 tor_assert(HT_EMPTY(&map
->head
));
1285 HT_CLEAR(strmap_impl
, &map
->head
);
1289 /** Remove all entries from <b>map</b>, and deallocate storage for those
1290 * entries. If free_val is provided, it is invoked on every value in
1294 digestmap_free(digestmap_t
*map
, void (*free_val
)(void*))
1296 digestmap_entry_t
**ent
, **next
, *this;
1299 for (ent
= HT_START(digestmap_impl
, &map
->head
); ent
!= NULL
; ent
= next
) {
1301 next
= HT_NEXT_RMV(digestmap_impl
, &map
->head
, ent
);
1303 free_val(this->val
);
1306 tor_assert(HT_EMPTY(&map
->head
));
1307 HT_CLEAR(digestmap_impl
, &map
->head
);
1311 /** Fail with an assertion error if anything has gone wrong with the internal
1312 * representation of <b>map</b>. */
1314 strmap_assert_ok(const strmap_t
*map
)
1316 tor_assert(!_strmap_impl_HT_REP_IS_BAD(&map
->head
));
1318 /** Fail with an assertion error if anything has gone wrong with the internal
1319 * representation of <b>map</b>. */
1321 digestmap_assert_ok(const digestmap_t
*map
)
1323 tor_assert(!_digestmap_impl_HT_REP_IS_BAD(&map
->head
));
1326 /** Return true iff <b>map</b> has no entries. */
1328 strmap_isempty(const strmap_t
*map
)
1330 return HT_EMPTY(&map
->head
);
1333 /** Return true iff <b>map</b> has no entries. */
1335 digestmap_isempty(const digestmap_t
*map
)
1337 return HT_EMPTY(&map
->head
);
1340 /** Return the number of items in <b>map</b>. */
1342 strmap_size(const strmap_t
*map
)
1344 return HT_SIZE(&map
->head
);
1347 /** Return the number of items in <b>map</b>. */
1349 digestmap_size(const digestmap_t
*map
)
1351 return HT_SIZE(&map
->head
);
1354 /** Declare a function called <b>funcname</b> that acts as a find_nth_FOO
1355 * function for an array of type <b>elt_t</b>*.
1357 * NOTE: The implementation kind of sucks: It's O(n log n), whereas finding
1358 * the kth element of an n-element list can be done in O(n). Then again, this
1359 * implementation is not in critical path, and it is obviously correct. */
1360 #define IMPLEMENT_ORDER_FUNC(funcname, elt_t) \
1362 _cmp_ ## elt_t(const void *_a, const void *_b) \
1364 const elt_t *a = _a, *b = _b; \
1373 funcname(elt_t *array, int n_elements, int nth) \
1375 tor_assert(nth >= 0); \
1376 tor_assert(nth < n_elements); \
1377 qsort(array, n_elements, sizeof(elt_t), _cmp_ ##elt_t); \
1378 return array[nth]; \
1381 IMPLEMENT_ORDER_FUNC(find_nth_int
, int)
1382 IMPLEMENT_ORDER_FUNC(find_nth_time
, time_t)
1383 IMPLEMENT_ORDER_FUNC(find_nth_double
, double)
1384 IMPLEMENT_ORDER_FUNC(find_nth_uint32
, uint32_t)
1385 IMPLEMENT_ORDER_FUNC(find_nth_int32
, int32_t)
1386 IMPLEMENT_ORDER_FUNC(find_nth_long
, long)
1388 /** Return a newly allocated digestset_t, optimized to hold a total of
1389 * <b>max_elements</b> digests with a reasonably low false positive weight. */
1391 digestset_new(int max_elements
)
1393 /* The probability of false positives is about P=(1 - exp(-kn/m))^k, where k
1394 * is the number of hash functions per entry, m is the bits in the array,
1395 * and n is the number of elements inserted. For us, k==4, n<=max_elements,
1396 * and m==n_bits= approximately max_elements*32. This gives
1397 * P<(1-exp(-4*n/(32*n)))^4 == (1-exp(1/-8))^4 == .00019
1399 * It would be more optimal in space vs false positives to get this false
1400 * positive rate by going for k==13, and m==18.5n, but we also want to
1401 * conserve CPU, and k==13 is pretty big.
1403 int n_bits
= 1u << (tor_log2(max_elements
)+5);
1404 digestset_t
*r
= tor_malloc(sizeof(digestset_t
));
1405 r
->mask
= n_bits
- 1;
1406 r
->ba
= bitarray_init_zero(n_bits
);
1410 /** Free all storage held in <b>set</b>. */
1412 digestset_free(digestset_t
*set
)
1416 bitarray_free(set
->ba
);