prepare for our emergency openssl fix release
[tor.git] / src / common / container.c
blob72f3470344caf7fba8e0911a40f08310b5585bbe
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 */
6 /**
7 * \file container.c
8 * \brief Implements a smartlist (a resizable array) along
9 * with helper functions to use smartlists. Also includes
10 * hash table implementations of a string-to-void* map, and of
11 * a digest-to-void* map.
12 **/
14 #include "compat.h"
15 #include "util.h"
16 #include "torlog.h"
17 #include "container.h"
18 #include "crypto.h"
20 #include <stdlib.h>
21 #include <string.h>
22 #include <assert.h>
24 #include "ht.h"
26 /** All newly allocated smartlists have this capacity. */
27 #define SMARTLIST_DEFAULT_CAPACITY 16
29 /** Allocate and return an empty smartlist.
31 smartlist_t *
32 smartlist_create(void)
34 smartlist_t *sl = tor_malloc(sizeof(smartlist_t));
35 sl->num_used = 0;
36 sl->capacity = SMARTLIST_DEFAULT_CAPACITY;
37 sl->list = tor_malloc(sizeof(void *) * sl->capacity);
38 return sl;
41 /** Deallocate a smartlist. Does not release storage associated with the
42 * list's elements.
44 void
45 smartlist_free(smartlist_t *sl)
47 if (!sl)
48 return;
49 tor_free(sl->list);
50 tor_free(sl);
53 /** Remove all elements from the list.
55 void
56 smartlist_clear(smartlist_t *sl)
58 sl->num_used = 0;
61 /** Make sure that <b>sl</b> can hold at least <b>size</b> entries. */
62 static INLINE void
63 smartlist_ensure_capacity(smartlist_t *sl, int size)
65 if (size > sl->capacity) {
66 int higher = sl->capacity * 2;
67 while (size > higher)
68 higher *= 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. */
76 void
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. */
84 void
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
96 * rearranged.
98 void
99 smartlist_remove(smartlist_t *sl, const void *element)
101 int i;
102 if (element == NULL)
103 return;
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,
112 * return NULL. */
113 void *
114 smartlist_pop_last(smartlist_t *sl)
116 tor_assert(sl);
117 if (sl->num_used)
118 return sl->list[--sl->num_used];
119 else
120 return NULL;
123 /** Reverse the order of the items in <b>sl</b>. */
124 void
125 smartlist_reverse(smartlist_t *sl)
127 int i, j;
128 void *tmp;
129 tor_assert(sl);
130 for (i = 0, j = sl->num_used-1; i < j; ++i, --j) {
131 tmp = sl->list[i];
132 sl->list[i] = sl->list[j];
133 sl->list[j] = tmp;
137 /** If there are any strings in sl equal to element, remove and free them.
138 * Does not preserve order. */
139 void
140 smartlist_string_remove(smartlist_t *sl, const char *element)
142 int i;
143 tor_assert(sl);
144 tor_assert(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)
159 int i;
160 for (i=0; i < sl->num_used; i++)
161 if (sl->list[i] == element)
162 return 1;
163 return 0;
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)
172 int i;
173 if (!sl) return 0;
174 for (i=0; i < sl->num_used; i++)
175 if (strcmp((const char*)sl->list[i],element)==0)
176 return 1;
177 return 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)
185 int i;
186 if (!sl) return -1;
187 for (i=0; i < sl->num_used; i++)
188 if (strcmp((const char*)sl->list[i],element)==0)
189 return i;
190 return -1;
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)
199 int i;
200 if (!sl) return 0;
201 for (i=0; i < sl->num_used; i++)
202 if (strcasecmp((const char*)sl->list[i],element)==0)
203 return 1;
204 return 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)
213 char buf[16];
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)
224 int i;
225 if (!sl) return 0;
226 for (i=0; i < sl->num_used; i++)
227 if (memcmp((const char*)sl->list[i],element,DIGEST_LEN)==0)
228 return 1;
229 return 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)
237 int i;
238 for (i=0; i < sl2->num_used; i++)
239 if (smartlist_isin(sl1, sl2->list[i]))
240 return 1;
241 return 0;
244 /** Remove every element E of sl1 such that !smartlist_isin(sl2,E).
245 * Does not preserve the order of sl1.
247 void
248 smartlist_intersect(smartlist_t *sl1, const smartlist_t *sl2)
250 int i;
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.
261 void
262 smartlist_subtract(smartlist_t *sl1, const smartlist_t *sl2)
264 int i;
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.
273 void
274 smartlist_del(smartlist_t *sl, int idx)
276 tor_assert(sl);
277 tor_assert(idx>=0);
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.
286 void
287 smartlist_del_keeporder(smartlist_t *sl, int idx)
289 tor_assert(sl);
290 tor_assert(idx>=0);
291 tor_assert(idx < sl->num_used);
292 --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
299 * forward one space.
301 void
302 smartlist_insert(smartlist_t *sl, int idx, void *val)
304 tor_assert(sl);
305 tor_assert(idx>=0);
306 tor_assert(idx <= sl->num_used);
307 if (idx == sl->num_used) {
308 smartlist_add(sl, val);
309 } else {
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));
315 sl->num_used++;
316 sl->list[idx] = val;
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>&amp;SPLIT_SKIP_SPACE is true, remove initial and
325 * trailing space from each entry.
326 * If <b>flags</b>&amp;SPLIT_IGNORE_BLANK is true, remove any entries
327 * of length 0.
328 * If <b>flags</b>&amp;SPLIT_STRIP_SPACE is true, strip spaces from each
329 * split string.
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,
336 int flags, int max)
338 const char *cp, *end, *next;
339 int n = 0;
341 tor_assert(sl);
342 tor_assert(str);
344 cp = str;
345 while (1) {
346 if (flags&SPLIT_SKIP_SPACE) {
347 while (TOR_ISSPACE(*cp)) ++cp;
350 if (max>0 && n == max-1) {
351 end = strchr(cp,'\0');
352 } else if (sep) {
353 end = strstr(cp,sep);
354 if (!end)
355 end = strchr(cp,'\0');
356 } else {
357 for (end = cp; *end && *end != '\t' && *end != ' '; ++end)
361 tor_assert(end);
363 if (!*end) {
364 next = NULL;
365 } else if (sep) {
366 next = end+strlen(sep);
367 } else {
368 next = end+1;
369 while (*next == '\t' || *next == ' ')
370 ++next;
373 if (flags&SPLIT_SKIP_SPACE) {
374 while (end > cp && TOR_ISSPACE(*(end-1)))
375 --end;
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);
382 ++n;
384 if (!next)
385 break;
386 cp = next;
389 return n;
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.
399 char *
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
409 * strings.)
411 char *
412 smartlist_join_strings2(smartlist_t *sl, const char *join,
413 size_t join_len, int terminate, size_t *len_out)
415 int i;
416 size_t n = 0;
417 char *r = NULL, *dst, *src;
419 tor_assert(sl);
420 tor_assert(join);
422 if (terminate)
423 n = join_len;
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 */
428 n += join_len;
430 dst = r = tor_malloc(n+1);
431 for (i = 0; i < sl->num_used; ) {
432 for (src = sl->list[i]; *src; )
433 *dst++ = *src++;
434 if (++i < sl->num_used) {
435 memcpy(dst, join, join_len);
436 dst += join_len;
439 if (terminate) {
440 memcpy(dst, join, join_len);
441 dst += join_len;
443 *dst = '\0';
445 if (len_out)
446 *len_out = dst-r;
447 return r;
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.
454 void
455 smartlist_sort(smartlist_t *sl, int (*compare)(const void **a, const void **b))
457 if (!sl->num_used)
458 return;
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.
467 void *
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;
475 int i, count=0;
477 if (!sl->num_used)
478 return NULL;
479 for (i = 0; i < sl->num_used; ++i) {
480 const void *item = sl->list[i];
481 if (cur && 0 == compare(&cur, &item)) {
482 ++count;
483 } else {
484 if (cur && count >= most_frequent_count) {
485 most_frequent = cur;
486 most_frequent_count = count;
488 cur = item;
489 count = 1;
492 if (cur && count >= most_frequent_count) {
493 most_frequent = cur;
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.
503 void
504 smartlist_uniq(smartlist_t *sl,
505 int (*compare)(const void **a, const void **b),
506 void (*free_fn)(void *a))
508 int i;
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) {
512 if (free_fn)
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.
524 void *
525 smartlist_bsearch(smartlist_t *sl, const void *key,
526 int (*compare)(const void *key, const void **member))
528 int found, idx;
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),
544 int *found_out)
546 int hi = smartlist_len(sl) - 1, lo = 0, cmp, mid;
548 while (lo <= hi) {
549 mid = (lo + hi) / 2;
550 cmp = compare(key, (const void**) &(sl->list[mid]));
551 if (cmp>0) { /* key > sl[mid] */
552 lo = mid+1;
553 } else if (cmp<0) { /* key < sl[mid] */
554 hi = mid-1;
555 } else { /* key == sl[mid] */
556 *found_out = 1;
557 return mid;
560 /* lo > hi. */
562 tor_assert(lo >= 0);
563 if (lo < smartlist_len(sl)) {
564 cmp = compare(key, (const void**) &(sl->list[lo]));
565 tor_assert(cmp < 0);
566 } else if (smartlist_len(sl)) {
567 cmp = compare(key, (const void**) &(sl->list[smartlist_len(sl)-1]));
568 tor_assert(cmp > 0);
571 *found_out = 0;
572 return lo;
575 /** Helper: compare two const char **s. */
576 static int
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
583 * order. */
584 void
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> */
591 char *
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().
599 void
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.
613 * Example:
615 * typedef struct timer_t {
616 * struct timeval tv;
617 * int heap_index;
618 * } 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) {
623 * return -1;
624 * } else if (t1->tv.tv_sec > t2->tv.tv_sec) {
625 * return 1;
626 * } else {
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),
633 * timer);
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; \
656 } while (0)
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. */
663 static INLINE void
664 smartlist_heapify(smartlist_t *sl,
665 int (*compare)(const void *a, const void *b),
666 int idx_field_offset,
667 int idx)
669 while (1) {
670 int left_idx = LEFT_CHILD(idx);
671 int best_idx;
673 if (left_idx >= sl->num_used)
674 return;
675 if (compare(sl->list[idx],sl->list[left_idx]) < 0)
676 best_idx = idx;
677 else
678 best_idx = left_idx;
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) {
684 return;
685 } else {
686 void *tmp = sl->list[idx];
687 sl->list[idx] = sl->list[best_idx];
688 sl->list[best_idx] = tmp;
689 UPDATE_IDX(idx);
690 UPDATE_IDX(best_idx);
692 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
700 * item.
702 void
703 smartlist_pqueue_add(smartlist_t *sl,
704 int (*compare)(const void *a, const void *b),
705 int idx_field_offset,
706 void *item)
708 int idx;
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];
717 sl->list[idx] = tmp;
718 UPDATE_IDX(parent);
719 UPDATE_IDX(idx);
720 idx = parent;
721 } else {
722 return;
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
730 * not be empty. */
731 void *
732 smartlist_pqueue_pop(smartlist_t *sl,
733 int (*compare)(const void *a, const void *b),
734 int idx_field_offset)
736 void *top;
737 tor_assert(sl->num_used);
739 top = sl->list[0];
740 *IDXP(top)=-1;
741 if (--sl->num_used) {
742 sl->list[0] = sl->list[sl->num_used];
743 UPDATE_IDX(0);
744 smartlist_heapify(sl, compare, idx_field_offset, 0);
746 return top;
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
752 * not be empty. */
753 void
754 smartlist_pqueue_remove(smartlist_t *sl,
755 int (*compare)(const void *a, const void *b),
756 int idx_field_offset,
757 void *item)
759 int idx = IDX_OF_ITEM(item);
760 tor_assert(idx >= 0);
761 tor_assert(sl->list[idx] == item);
762 --sl->num_used;
763 *IDXP(item) = -1;
764 if (idx == sl->num_used) {
765 return;
766 } else {
767 sl->list[idx] = sl->list[sl->num_used];
768 UPDATE_IDX(idx);
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>. */
775 void
776 smartlist_pqueue_assert_ok(smartlist_t *sl,
777 int (*compare)(const void *a, const void *b),
778 int idx_field_offset)
780 int i;
781 for (i = sl->num_used - 1; i >= 0; --i) {
782 if (i>0)
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. */
789 static int
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. */
796 void
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().
804 void
805 smartlist_uniq_digests(smartlist_t *sl)
807 smartlist_uniq(sl, _compare_digests, _tor_free);
810 /** Helper: compare two DIGEST256_LEN digests. */
811 static int
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. */
818 void
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> */
826 char *
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
833 * tor_free().
835 void
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; \
848 void *val; \
849 keydecl; \
850 } prefix ## entry_t; \
851 struct maptype { \
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. */
859 static INLINE int
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. */
873 static INLINE int
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)
883 #if SIZEOF_INT != 8
884 const uint32_t *p = (const uint32_t*)a->key;
885 return p[0] ^ p[1] ^ p[2] ^ p[3] ^ p[4];
886 #else
887 const uint64_t *p = (const uint64_t*)a->key;
888 return p[0] ^ p[1];
889 #endif
892 HT_PROTOTYPE(strmap_impl, strmap_entry_t, node, strmap_entry_hash,
893 strmap_entries_eq)
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.
904 strmap_t *
905 strmap_new(void)
907 strmap_t *result;
908 result = tor_malloc(sizeof(strmap_t));
909 HT_INIT(strmap_impl, &result->head);
910 return result;
913 /** Constructor to create a new empty map from digests to void*'s.
915 digestmap_t *
916 digestmap_new(void)
918 digestmap_t *result;
919 result = tor_malloc(sizeof(digestmap_t));
920 HT_INIT(digestmap_impl, &result->head);
921 return result;
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
928 * <b>val</b>.
930 void *
931 strmap_set(strmap_t *map, const char *key, void *val)
933 strmap_entry_t *resolve;
934 strmap_entry_t search;
935 void *oldval;
936 tor_assert(map);
937 tor_assert(key);
938 tor_assert(val);
939 search.key = (char*)key;
940 resolve = HT_FIND(strmap_impl, &map->head, &search);
941 if (resolve) {
942 oldval = resolve->val;
943 resolve->val = val;
944 return oldval;
945 } else {
946 resolve = tor_malloc_zero(sizeof(strmap_entry_t));
947 resolve->key = tor_strdup(key);
948 resolve->val = val;
949 tor_assert(!HT_FIND(strmap_impl, &map->head, resolve));
950 HT_INSERT(strmap_impl, &map->head, resolve);
951 return NULL;
955 #define OPTIMIZED_DIGESTMAP_SET
957 /** Like strmap_set() above but for digestmaps. */
958 void *
959 digestmap_set(digestmap_t *map, const char *key, void *val)
961 #ifndef OPTIMIZED_DIGESTMAP_SET
962 digestmap_entry_t *resolve;
963 #endif
964 digestmap_entry_t search;
965 void *oldval;
966 tor_assert(map);
967 tor_assert(key);
968 tor_assert(val);
969 memcpy(&search.key, key, DIGEST_LEN);
970 #ifndef OPTIMIZED_DIGESTMAP_SET
971 resolve = HT_FIND(digestmap_impl, &map->head, &search);
972 if (resolve) {
973 oldval = resolve->val;
974 resolve->val = val;
975 return oldval;
976 } else {
977 resolve = tor_malloc_zero(sizeof(digestmap_entry_t));
978 memcpy(resolve->key, key, DIGEST_LEN);
979 resolve->val = val;
980 HT_INSERT(digestmap_impl, &map->head, resolve);
981 return NULL;
983 #else
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;
994 (*ptr)->val = val;
995 return oldval;
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);
1002 newent->val = val;
1003 _HT_FOI_INSERT(node, &(map->head), &search, newent, ptr);
1004 return NULL;
1006 #endif
1009 /** Return the current value associated with <b>key</b>, or NULL if no
1010 * value is set.
1012 void *
1013 strmap_get(const strmap_t *map, const char *key)
1015 strmap_entry_t *resolve;
1016 strmap_entry_t search;
1017 tor_assert(map);
1018 tor_assert(key);
1019 search.key = (char*)key;
1020 resolve = HT_FIND(strmap_impl, &map->head, &search);
1021 if (resolve) {
1022 return resolve->val;
1023 } else {
1024 return NULL;
1028 /** Like strmap_get() above but for digestmaps. */
1029 void *
1030 digestmap_get(const digestmap_t *map, const char *key)
1032 digestmap_entry_t *resolve;
1033 digestmap_entry_t search;
1034 tor_assert(map);
1035 tor_assert(key);
1036 memcpy(&search.key, key, DIGEST_LEN);
1037 resolve = HT_FIND(digestmap_impl, &map->head, &search);
1038 if (resolve) {
1039 return resolve->val;
1040 } else {
1041 return NULL;
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
1047 * <b>key</b>.
1049 * Note: you must free any storage associated with the returned value.
1051 void *
1052 strmap_remove(strmap_t *map, const char *key)
1054 strmap_entry_t *resolve;
1055 strmap_entry_t search;
1056 void *oldval;
1057 tor_assert(map);
1058 tor_assert(key);
1059 search.key = (char*)key;
1060 resolve = HT_REMOVE(strmap_impl, &map->head, &search);
1061 if (resolve) {
1062 oldval = resolve->val;
1063 tor_free(resolve->key);
1064 tor_free(resolve);
1065 return oldval;
1066 } else {
1067 return NULL;
1071 /** Like strmap_remove() above but for digestmaps. */
1072 void *
1073 digestmap_remove(digestmap_t *map, const char *key)
1075 digestmap_entry_t *resolve;
1076 digestmap_entry_t search;
1077 void *oldval;
1078 tor_assert(map);
1079 tor_assert(key);
1080 memcpy(&search.key, key, DIGEST_LEN);
1081 resolve = HT_REMOVE(digestmap_impl, &map->head, &search);
1082 if (resolve) {
1083 oldval = resolve->val;
1084 tor_free(resolve);
1085 return oldval;
1086 } else {
1087 return NULL;
1091 /** Same as strmap_set, but first converts <b>key</b> to lowercase. */
1092 void *
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. */
1097 void *v;
1098 char *lc_key = tor_strdup(key);
1099 tor_strlower(lc_key);
1100 v = strmap_set(map,lc_key,val);
1101 tor_free(lc_key);
1102 return v;
1105 /** Same as strmap_get, but first converts <b>key</b> to lowercase. */
1106 void *
1107 strmap_get_lc(const strmap_t *map, const char *key)
1109 void *v;
1110 char *lc_key = tor_strdup(key);
1111 tor_strlower(lc_key);
1112 v = strmap_get(map,lc_key);
1113 tor_free(lc_key);
1114 return v;
1117 /** Same as strmap_remove, but first converts <b>key</b> to lowercase */
1118 void *
1119 strmap_remove_lc(strmap_t *map, const char *key)
1121 void *v;
1122 char *lc_key = tor_strdup(key);
1123 tor_strlower(lc_key);
1124 v = strmap_remove(map,lc_key);
1125 tor_free(lc_key);
1126 return v;
1129 /** return an <b>iterator</b> pointer to the front of a map.
1131 * Iterator example:
1133 * \code
1134 * // uppercase values in "map", removing empty values.
1136 * strmap_iter_t *iter;
1137 * const char *key;
1138 * void *val;
1139 * char *cp;
1141 * for (iter = strmap_iter_init(map); !strmap_iter_done(iter); ) {
1142 * strmap_iter_get(iter, &key, &val);
1143 * cp = (char*)val;
1144 * if (!*cp) {
1145 * iter = strmap_iter_next_rmv(map,iter);
1146 * free(val);
1147 * } else {
1148 * for (;*cp;cp++) *cp = TOR_TOUPPER(*cp);
1149 * iter = strmap_iter_next(map,iter);
1152 * \endcode
1155 strmap_iter_t *
1156 strmap_iter_init(strmap_t *map)
1158 tor_assert(map);
1159 return HT_START(strmap_impl, &map->head);
1162 /** Start iterating through <b>map</b>. See strmap_iter_init() for example. */
1163 digestmap_iter_t *
1164 digestmap_iter_init(digestmap_t *map)
1166 tor_assert(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. */
1172 strmap_iter_t *
1173 strmap_iter_next(strmap_t *map, strmap_iter_t *iter)
1175 tor_assert(map);
1176 tor_assert(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. */
1182 digestmap_iter_t *
1183 digestmap_iter_next(digestmap_t *map, digestmap_iter_t *iter)
1185 tor_assert(map);
1186 tor_assert(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.
1193 strmap_iter_t *
1194 strmap_iter_next_rmv(strmap_t *map, strmap_iter_t *iter)
1196 strmap_entry_t *rmv;
1197 tor_assert(map);
1198 tor_assert(iter);
1199 tor_assert(*iter);
1200 rmv = *iter;
1201 iter = HT_NEXT_RMV(strmap_impl, &map->head, iter);
1202 tor_free(rmv->key);
1203 tor_free(rmv);
1204 return 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.
1210 digestmap_iter_t *
1211 digestmap_iter_next_rmv(digestmap_t *map, digestmap_iter_t *iter)
1213 digestmap_entry_t *rmv;
1214 tor_assert(map);
1215 tor_assert(iter);
1216 tor_assert(*iter);
1217 rmv = *iter;
1218 iter = HT_NEXT_RMV(digestmap_impl, &map->head, iter);
1219 tor_free(rmv);
1220 return iter;
1223 /** Set *<b>keyp</b> and *<b>valp</b> to the current entry pointed to by
1224 * iter. */
1225 void
1226 strmap_iter_get(strmap_iter_t *iter, const char **keyp, void **valp)
1228 tor_assert(iter);
1229 tor_assert(*iter);
1230 tor_assert(keyp);
1231 tor_assert(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
1237 * iter. */
1238 void
1239 digestmap_iter_get(digestmap_iter_t *iter, const char **keyp, void **valp)
1241 tor_assert(iter);
1242 tor_assert(*iter);
1243 tor_assert(keyp);
1244 tor_assert(valp);
1245 *keyp = (*iter)->key;
1246 *valp = (*iter)->val;
1249 /** Return true iff <b>iter</b> has advanced past the last entry of
1250 * <b>map</b>. */
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
1258 * <b>map</b>. */
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
1267 * <b>map</b>.
1269 void
1270 strmap_free(strmap_t *map, void (*free_val)(void*))
1272 strmap_entry_t **ent, **next, *this;
1273 if (!map)
1274 return;
1276 for (ent = HT_START(strmap_impl, &map->head); ent != NULL; ent = next) {
1277 this = *ent;
1278 next = HT_NEXT_RMV(strmap_impl, &map->head, ent);
1279 tor_free(this->key);
1280 if (free_val)
1281 free_val(this->val);
1282 tor_free(this);
1284 tor_assert(HT_EMPTY(&map->head));
1285 HT_CLEAR(strmap_impl, &map->head);
1286 tor_free(map);
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
1291 * <b>map</b>.
1293 void
1294 digestmap_free(digestmap_t *map, void (*free_val)(void*))
1296 digestmap_entry_t **ent, **next, *this;
1297 if (!map)
1298 return;
1299 for (ent = HT_START(digestmap_impl, &map->head); ent != NULL; ent = next) {
1300 this = *ent;
1301 next = HT_NEXT_RMV(digestmap_impl, &map->head, ent);
1302 if (free_val)
1303 free_val(this->val);
1304 tor_free(this);
1306 tor_assert(HT_EMPTY(&map->head));
1307 HT_CLEAR(digestmap_impl, &map->head);
1308 tor_free(map);
1311 /** Fail with an assertion error if anything has gone wrong with the internal
1312 * representation of <b>map</b>. */
1313 void
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>. */
1320 void
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) \
1361 static int \
1362 _cmp_ ## elt_t(const void *_a, const void *_b) \
1364 const elt_t *a = _a, *b = _b; \
1365 if (*a<*b) \
1366 return -1; \
1367 else if (*a>*b) \
1368 return 1; \
1369 else \
1370 return 0; \
1372 elt_t \
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. */
1390 digestset_t *
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);
1407 return r;
1410 /** Free all storage held in <b>set</b>. */
1411 void
1412 digestset_free(digestset_t *set)
1414 if (!set)
1415 return;
1416 bitarray_free(set->ba);
1417 tor_free(set);