even better function start checks; give dmalloc a chance of working.
[tor.git] / src / common / container.c
blob39cabe9c5dcd877727f0cb000deabac4b959ffcb
1 /* Copyright 2003-2004 Roger Dingledine
2 Copyright 2004-2005 Roger Dingledine, Nick Mathewson */
3 /* See LICENSE for licensing information */
4 /* $Id$ */
5 const char container_c_id[] = "$Id$";
7 /**
8 * \file container.c
9 * \brief Implements a smartlist (a resizable array) along
10 * with helper functions to use smartlists. Also includes a
11 * splay-tree implementation of the string-to-void* map.
12 **/
14 #include "compat.h"
15 #include "util.h"
16 #include "log.h"
17 #include "../or/tree.h"
18 #include "container.h"
20 #ifdef HAVE_CTYPE_H
21 #include <ctype.h>
22 #endif
23 #include <stdlib.h>
24 #include <string.h>
25 #include <assert.h>
27 /* All newly allocated smartlists have this capacity.
29 #define SMARTLIST_DEFAULT_CAPACITY 32
31 #ifndef FAST_SMARTLIST
32 struct smartlist_t {
33 /** <b>list</b> has enough capacity to store exactly <b>capacity</b> elements
34 * before it needs to be resized. Only the first <b>num_used</b> (\<=
35 * capacity) elements point to valid data.
37 void **list;
38 int num_used;
39 int capacity;
41 #endif
43 /** Allocate and return an empty smartlist.
45 smartlist_t *
46 smartlist_create(void)
48 smartlist_t *sl = tor_malloc(sizeof(smartlist_t));
49 sl->num_used = 0;
50 sl->capacity = SMARTLIST_DEFAULT_CAPACITY;
51 sl->list = tor_malloc(sizeof(void *) * sl->capacity);
52 return sl;
55 /** Deallocate a smartlist. Does not release storage associated with the
56 * list's elements.
58 void
59 smartlist_free(smartlist_t *sl)
61 free(sl->list);
62 free(sl);
65 /** Change the capacity of the smartlist to <b>n</b>, so that we can grow
66 * the list up to <b>n</b> elements with no further reallocation or wasted
67 * space. If <b>n</b> is less than or equal to the number of elements
68 * currently in the list, reduce the list's capacity as much as
69 * possible without losing elements.
71 void
72 smartlist_set_capacity(smartlist_t *sl, int n)
74 if (n < sl->num_used)
75 n = sl->num_used;
76 if (sl->capacity != n) {
77 sl->capacity = n;
78 sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
82 /** Remove all elements from the list.
84 void
85 smartlist_clear(smartlist_t *sl)
87 sl->num_used = 0;
90 /** Set the list's new length to <b>len</b> (which must be \<= the list's
91 * current size). Remove the last smartlist_len(sl)-len elements from the
92 * list.
94 void
95 smartlist_truncate(smartlist_t *sl, int len)
97 tor_assert(len <= sl->num_used);
98 sl->num_used = len;
101 /** Append element to the end of the list. */
102 void
103 smartlist_add(smartlist_t *sl, void *element)
105 if (sl->num_used >= sl->capacity) {
106 int higher = sl->capacity * 2;
107 tor_assert(higher > sl->capacity); /* detect overflow */
108 sl->capacity = higher;
109 sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
111 sl->list[sl->num_used++] = element;
114 /** Append each element from S2 to the end of S1. */
115 void
116 smartlist_add_all(smartlist_t *sl, const smartlist_t *s2)
118 int n2 = sl->num_used + s2->num_used;
119 if (n2 > sl->capacity) {
120 int higher = sl->capacity * 2;
121 while (n2 > higher)
122 higher *= 2;
123 sl->capacity = higher;
124 sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
126 memcpy(sl->list + sl->num_used, s2->list, s2->num_used*sizeof(void*));
127 sl->num_used += s2->num_used;
130 /** Remove all elements E from sl such that E==element. Preserve
131 * the order of any elements before E, but elements after E can be
132 * rearranged.
134 void
135 smartlist_remove(smartlist_t *sl, void *element)
137 int i;
138 if (element == NULL)
139 return;
140 for (i=0; i < sl->num_used; i++)
141 if (sl->list[i] == element) {
142 sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
143 i--; /* so we process the new i'th element */
147 /** If there are any strings in sl equal to element, remove and free them.
148 * Does not preserve order. */
149 void
150 smartlist_string_remove(smartlist_t *sl, const char *element)
152 int i;
153 tor_assert(sl);
154 tor_assert(element);
155 for (i = 0; i < sl->num_used; ++i) {
156 if (!strcmp(element, sl->list[i])) {
157 tor_free(sl->list[i]);
158 sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
159 i--; /* so we process the new i'th element */
164 /** Return true iff some element E of sl has E==element.
167 smartlist_isin(const smartlist_t *sl, void *element)
169 int i;
170 for (i=0; i < sl->num_used; i++)
171 if (sl->list[i] == element)
172 return 1;
173 return 0;
176 /** Return true iff <b>sl</b> has some element E such that
177 * !strcmp(E,<b>element</b>)
180 smartlist_string_isin(const smartlist_t *sl, const char *element)
182 int i;
183 if (!sl) return 0;
184 for (i=0; i < sl->num_used; i++)
185 if (strcmp((const char*)sl->list[i],element)==0)
186 return 1;
187 return 0;
190 /** Return true iff <b>sl</b> has some element E such that E is equal
191 * to the decimal encoding of <b>num</b>.
194 smartlist_string_num_isin(const smartlist_t *sl, int num)
196 char buf[16];
197 tor_snprintf(buf,sizeof(buf),"%d", num);
198 return smartlist_string_isin(sl, buf);
201 /** Return true iff some element E of sl2 has smartlist_isin(sl1,E).
204 smartlist_overlap(const smartlist_t *sl1, const smartlist_t *sl2)
206 int i;
207 for (i=0; i < sl2->num_used; i++)
208 if (smartlist_isin(sl1, sl2->list[i]))
209 return 1;
210 return 0;
213 /** Remove every element E of sl1 such that !smartlist_isin(sl2,E).
214 * Does not preserve the order of sl1.
216 void
217 smartlist_intersect(smartlist_t *sl1, const smartlist_t *sl2)
219 int i;
220 for (i=0; i < sl1->num_used; i++)
221 if (!smartlist_isin(sl2, sl1->list[i])) {
222 sl1->list[i] = sl1->list[--sl1->num_used]; /* swap with the end */
223 i--; /* so we process the new i'th element */
227 /** Remove every element E of sl1 such that smartlist_isin(sl2,E).
228 * Does not preserve the order of sl1.
230 void
231 smartlist_subtract(smartlist_t *sl1, const smartlist_t *sl2)
233 int i;
234 for (i=0; i < sl2->num_used; i++)
235 smartlist_remove(sl1, sl2->list[i]);
238 #ifndef FAST_SMARTLIST
239 /** Return the <b>idx</b>th element of sl.
241 void *
242 smartlist_get(const smartlist_t *sl, int idx)
244 tor_assert(sl);
245 tor_assert(idx>=0);
246 tor_assert(idx < sl->num_used);
247 return sl->list[idx];
249 /** Change the value of the <b>idx</b>th element of sl to <b>val</b>.
251 void
252 smartlist_set(smartlist_t *sl, int idx, void *val)
254 tor_assert(sl);
255 tor_assert(idx>=0);
256 tor_assert(idx < sl->num_used);
257 sl->list[idx] = val;
259 /** Return the number of items in sl.
262 smartlist_len(const smartlist_t *sl)
264 return sl->num_used;
266 #endif
268 /** Remove the <b>idx</b>th element of sl; if idx is not the last
269 * element, swap the last element of sl into the <b>idx</b>th space.
270 * Return the old value of the <b>idx</b>th element.
272 void
273 smartlist_del(smartlist_t *sl, int idx)
275 tor_assert(sl);
276 tor_assert(idx>=0);
277 tor_assert(idx < sl->num_used);
278 sl->list[idx] = sl->list[--sl->num_used];
280 /** Remove the <b>idx</b>th element of sl; if idx is not the last element,
281 * moving all subsequent elements back one space. Return the old value
282 * of the <b>idx</b>th element.
284 void
285 smartlist_del_keeporder(smartlist_t *sl, int idx)
287 tor_assert(sl);
288 tor_assert(idx>=0);
289 tor_assert(idx < sl->num_used);
290 --sl->num_used;
291 if (idx < sl->num_used)
292 memmove(sl->list+idx, sl->list+idx+1, sizeof(void*)*(sl->num_used-idx));
294 /** Insert the value <b>val</b> as the new <b>idx</b>th element of
295 * <b>sl</b>, moving all items previously at <b>idx</b> or later
296 * forward one space.
298 void
299 smartlist_insert(smartlist_t *sl, int idx, void *val)
301 tor_assert(sl);
302 tor_assert(idx>=0);
303 tor_assert(idx <= sl->num_used);
304 if (idx == sl->num_used) {
305 smartlist_add(sl, val);
306 } else {
307 /* Ensure sufficient capacity */
308 if (sl->num_used >= sl->capacity) {
309 sl->capacity *= 2;
310 sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
312 /* Move other elements away */
313 if (idx < sl->num_used)
314 memmove(sl->list + idx + 1, sl->list + idx,
315 sizeof(void*)*(sl->num_used-idx));
316 sl->num_used++;
317 sl->list[idx] = val;
322 * Split a string <b>str</b> along all occurrences of <b>sep</b>,
323 * adding the split strings, in order, to <b>sl</b>. If
324 * <b>flags</b>&amp;SPLIT_SKIP_SPACE is true, remove initial and
325 * trailing space from each entry. If
326 * <b>flags</b>&amp;SPLIT_IGNORE_BLANK is true, remove any entries of
327 * length 0. If max>0, divide the string into no more than <b>max</b>
328 * pieces. If <b>sep</b> is NULL, split on any sequence of horizontal space.
331 smartlist_split_string(smartlist_t *sl, const char *str, const char *sep,
332 int flags, int max)
334 const char *cp, *end, *next;
335 int n = 0;
337 tor_assert(sl);
338 tor_assert(str);
340 cp = str;
341 while (1) {
342 if (flags&SPLIT_SKIP_SPACE) {
343 while (TOR_ISSPACE(*cp)) ++cp;
346 if (max>0 && n == max-1) {
347 end = strchr(cp,'\0');
348 } else if (sep) {
349 end = strstr(cp,sep);
350 if (!end)
351 end = strchr(cp,'\0');
352 } else {
353 for (end = cp; *end && *end != '\t' && *end != ' '; ++end)
357 if (!*end) {
358 next = NULL;
359 } else if (sep) {
360 next = end+strlen(sep);
361 } else {
362 next = end+1;
363 while (*next == '\t' || *next == ' ')
364 ++next;
367 if (flags&SPLIT_SKIP_SPACE) {
368 while (end > cp && TOR_ISSPACE(*(end-1)))
369 --end;
371 if (end != cp || !(flags&SPLIT_IGNORE_BLANK)) {
372 smartlist_add(sl, tor_strndup(cp, end-cp));
373 ++n;
375 if (!next)
376 break;
377 cp = next;
380 return n;
383 /** Allocate and return a new string containing the concatenation of
384 * the elements of <b>sl</b>, in order, separated by <b>join</b>. If
385 * <b>terminate</b> is true, also terminate the string with <b>join</b>.
386 * If <b>len_out</b> is not NULL, set <b>len_out</b> to the length of
387 * the returned string. Requires that every element of <b>sl</b> is
388 * NUL-terminated string.
390 char *
391 smartlist_join_strings(smartlist_t *sl, const char *join,
392 int terminate, size_t *len_out)
394 return smartlist_join_strings2(sl,join,strlen(join),terminate,len_out);
397 /** As smartlist_join_strings, but instead of separating/terminated with a
398 * NUL-terminated string <b>join</b>, uses the <b>join_len</b>-byte sequence
399 * at <b>join</b>. (Useful for generating a sequence of NUL-terminated
400 * strings.)
402 char *
403 smartlist_join_strings2(smartlist_t *sl, const char *join,
404 size_t join_len, int terminate, size_t *len_out)
406 int i;
407 size_t n = 0;
408 char *r = NULL, *dst, *src;
410 tor_assert(sl);
411 tor_assert(join);
413 if (terminate)
414 n = join_len;
416 for (i = 0; i < sl->num_used; ++i) {
417 n += strlen(sl->list[i]);
418 if (i+1 < sl->num_used) /* avoid double-counting the last one */
419 n += join_len;
421 dst = r = tor_malloc(n+1);
422 for (i = 0; i < sl->num_used; ) {
423 for (src = sl->list[i]; *src; )
424 *dst++ = *src++;
425 if (++i < sl->num_used) {
426 memcpy(dst, join, join_len);
427 dst += join_len;
430 if (terminate) {
431 memcpy(dst, join, join_len);
432 dst += join_len;
434 *dst = '\0';
436 if (len_out)
437 *len_out = dst-r;
438 return r;
441 /** Sort the members of <b>sl</b> into an order defined by
442 * the ordering function <b>compare</b>, which returns less then 0 if a
443 * precedes b, greater than 0 if b precedes a, and 0 if a 'equals' b.
445 void
446 smartlist_sort(smartlist_t *sl, int (*compare)(const void **a, const void **b))
448 if (!sl->num_used)
449 return;
450 qsort(sl->list, sl->num_used, sizeof(void*),
451 (int (*)(const void *,const void*))compare);
454 /** Assuming the members of <b>sl</b> are in order, return a pointer to the
455 * member which matches <b>key</b>. Ordering and matching are defined by a
456 * <b>compare</b> function, which returns 0 on a match; less than 0 if key is
457 * less than member, and greater than 0 if key is greater then member.
459 void *
460 smartlist_bsearch(smartlist_t *sl, const void *key,
461 int (*compare)(const void *key, const void **member))
463 void ** r;
464 if (!sl->num_used)
465 return NULL;
467 r = bsearch(key, sl->list, sl->num_used, sizeof(void*),
468 (int (*)(const void *, const void *))compare);
469 return r ? *r : NULL;
472 /** Helper: compare two const char **s. */
473 static int
474 _compare_string_ptrs(const void **_a, const void **_b)
476 return strcmp((const char*)*_a, (const char*)*_b);
479 /** Sort a smartlist <b>sl</b> containing strings into lexically ascending
480 * order. */
481 void
482 smartlist_sort_strings(smartlist_t *sl)
484 smartlist_sort(sl, _compare_string_ptrs);
487 /** Splay-tree implementation of string-to-void* map
489 typedef struct strmap_entry_t {
490 SPLAY_ENTRY(strmap_entry_t) node;
491 char *key;
492 void *val;
493 } strmap_entry_t;
495 struct strmap_t {
496 SPLAY_HEAD(strmap_tree, strmap_entry_t) head;
499 /** Helper: compare strmap_entry_t objects by key value. */
500 static int
501 compare_strmap_entries(strmap_entry_t *a,
502 strmap_entry_t *b)
504 return strcmp(a->key, b->key);
507 SPLAY_PROTOTYPE(strmap_tree, strmap_entry_t, node, compare_strmap_entries);
508 SPLAY_GENERATE(strmap_tree, strmap_entry_t, node, compare_strmap_entries);
510 /** Create a new empty map from strings to void*'s.
512 strmap_t *
513 strmap_new(void)
515 strmap_t *result;
516 result = tor_malloc(sizeof(strmap_t));
517 SPLAY_INIT(&result->head);
518 return result;
521 /** Set the current value for <b>key</b> to <b>val</b>. Returns the previous
522 * value for <b>key</b> if one was set, or NULL if one was not.
524 * This function makes a copy of <b>key</b> if necessary, but not of <b>val</b>.
526 void *
527 strmap_set(strmap_t *map, const char *key, void *val)
529 strmap_entry_t *resolve;
530 strmap_entry_t search;
531 void *oldval;
532 tor_assert(map);
533 tor_assert(key);
534 tor_assert(val);
535 search.key = (char*)key;
536 resolve = SPLAY_FIND(strmap_tree, &map->head, &search);
537 if (resolve) {
538 oldval = resolve->val;
539 resolve->val = val;
540 return oldval;
541 } else {
542 resolve = tor_malloc_zero(sizeof(strmap_entry_t));
543 resolve->key = tor_strdup(key);
544 resolve->val = val;
545 SPLAY_INSERT(strmap_tree, &map->head, resolve);
546 return NULL;
550 /** Return the current value associated with <b>key</b>, or NULL if no
551 * value is set.
553 void *
554 strmap_get(strmap_t *map, const char *key)
556 strmap_entry_t *resolve;
557 strmap_entry_t search;
558 tor_assert(map);
559 tor_assert(key);
560 search.key = (char*)key;
561 resolve = SPLAY_FIND(strmap_tree, &map->head, &search);
562 if (resolve) {
563 return resolve->val;
564 } else {
565 return NULL;
569 /** Remove the value currently associated with <b>key</b> from the map.
570 * Return the value if one was set, or NULL if there was no entry for
571 * <b>key</b>.
573 * Note: you must free any storage associated with the returned value.
575 void *
576 strmap_remove(strmap_t *map, const char *key)
578 strmap_entry_t *resolve;
579 strmap_entry_t search;
580 void *oldval;
581 tor_assert(map);
582 tor_assert(key);
583 search.key = (char*)key;
584 resolve = SPLAY_FIND(strmap_tree, &map->head, &search);
585 if (resolve) {
586 oldval = resolve->val;
587 SPLAY_REMOVE(strmap_tree, &map->head, resolve);
588 tor_free(resolve->key);
589 tor_free(resolve);
590 return oldval;
591 } else {
592 return NULL;
596 /** Same as strmap_set, but first converts <b>key</b> to lowercase. */
597 void *
598 strmap_set_lc(strmap_t *map, const char *key, void *val)
600 /* We could be a little faster by using strcasecmp instead, and a separate
601 * type, but I don't think it matters. */
602 void *v;
603 char *lc_key = tor_strdup(key);
604 tor_strlower(lc_key);
605 v = strmap_set(map,lc_key,val);
606 tor_free(lc_key);
607 return v;
609 /** Same as strmap_get, but first converts <b>key</b> to lowercase. */
610 void *
611 strmap_get_lc(strmap_t *map, const char *key)
613 void *v;
614 char *lc_key = tor_strdup(key);
615 tor_strlower(lc_key);
616 v = strmap_get(map,lc_key);
617 tor_free(lc_key);
618 return v;
620 /** Same as strmap_remove, but first converts <b>key</b> to lowercase */
621 void *
622 strmap_remove_lc(strmap_t *map, const char *key)
624 void *v;
625 char *lc_key = tor_strdup(key);
626 tor_strlower(lc_key);
627 v = strmap_remove(map,lc_key);
628 tor_free(lc_key);
629 return v;
632 /** Invoke fn() on every entry of the map, in order. For every entry,
633 * fn() is invoked with that entry's key, that entry's value, and the
634 * value of <b>data</b> supplied to strmap_foreach. fn() must return a new
635 * (possibly unmodified) value for each entry: if fn() returns NULL, the
636 * entry is removed.
638 * Example:
639 * \code
640 * static void* upcase_and_remove_empty_vals(const char *key, void *val,
641 * void* data) {
642 * char *cp = (char*)val;
643 * if (!*cp) { // val is an empty string.
644 * free(val);
645 * return NULL;
646 * } else {
647 * for (; *cp; cp++)
648 * *cp = toupper(*cp);
650 * return val;
654 * ...
656 * strmap_foreach(map, upcase_and_remove_empty_vals, NULL);
657 * \endcode
659 void
660 strmap_foreach(strmap_t *map,
661 void* (*fn)(const char *key, void *val, void *data),
662 void *data)
664 strmap_entry_t *ptr, *next;
665 tor_assert(map);
666 tor_assert(fn);
667 for (ptr = SPLAY_MIN(strmap_tree, &map->head); ptr != NULL; ptr = next) {
668 /* This remove-in-place usage is specifically blessed in tree(3). */
669 next = SPLAY_NEXT(strmap_tree, &map->head, ptr);
670 ptr->val = fn(ptr->key, ptr->val, data);
671 if (!ptr->val) {
672 SPLAY_REMOVE(strmap_tree, &map->head, ptr);
673 tor_free(ptr->key);
674 tor_free(ptr);
679 /** return an <b>iterator</b> pointer to the front of a map.
681 * Iterator example:
683 * \code
684 * // uppercase values in "map", removing empty values.
686 * strmap_iter_t *iter;
687 * const char *key;
688 * void *val;
689 * char *cp;
691 * for (iter = strmap_iter_init(map); !strmap_iter_done(iter); ) {
692 * strmap_iter_get(iter, &key, &val);
693 * cp = (char*)val;
694 * if (!*cp) {
695 * iter = strmap_iter_next_rmv(iter);
696 * free(val);
697 * } else {
698 * for (;*cp;cp++) *cp = toupper(*cp);
699 * iter = strmap_iter_next(iter);
702 * \endcode
705 strmap_iter_t *
706 strmap_iter_init(strmap_t *map)
708 tor_assert(map);
709 return SPLAY_MIN(strmap_tree, &map->head);
711 /** Advance the iterator <b>iter</b> for map a single step to the next entry.
713 strmap_iter_t *
714 strmap_iter_next(strmap_t *map, strmap_iter_t *iter)
716 tor_assert(map);
717 tor_assert(iter);
718 return SPLAY_NEXT(strmap_tree, &map->head, iter);
720 /** Advance the iterator <b>iter</b> a single step to the next entry, removing
721 * the current entry.
723 strmap_iter_t *
724 strmap_iter_next_rmv(strmap_t *map, strmap_iter_t *iter)
726 strmap_iter_t *next;
727 tor_assert(map);
728 tor_assert(iter);
729 next = SPLAY_NEXT(strmap_tree, &map->head, iter);
730 SPLAY_REMOVE(strmap_tree, &map->head, iter);
731 tor_free(iter->key);
732 tor_free(iter);
733 return next;
735 /** Set *keyp and *valp to the current entry pointed to by iter.
737 void
738 strmap_iter_get(strmap_iter_t *iter, const char **keyp, void **valp)
740 tor_assert(iter);
741 tor_assert(keyp);
742 tor_assert(valp);
743 *keyp = iter->key;
744 *valp = iter->val;
746 /** Return true iff iter has advanced past the last entry of map.
749 strmap_iter_done(strmap_iter_t *iter)
751 return iter == NULL;
753 /** Remove all entries from <b>map</b>, and deallocate storage for those entries.
754 * If free_val is provided, it is invoked on every value in <b>map</b>.
756 void
757 strmap_free(strmap_t *map, void (*free_val)(void*))
759 strmap_entry_t *ent, *next;
760 for (ent = SPLAY_MIN(strmap_tree, &map->head); ent != NULL; ent = next) {
761 next = SPLAY_NEXT(strmap_tree, &map->head, ent);
762 SPLAY_REMOVE(strmap_tree, &map->head, ent);
763 tor_free(ent->key);
764 if (free_val)
765 free_val(ent->val);
766 tor_free(ent);
768 tor_assert(SPLAY_EMPTY(&map->head));
769 tor_free(map);
772 /* Return true iff <b>map</b> has no entries.
775 strmap_isempty(strmap_t *map)
777 return SPLAY_EMPTY(&map->head);