Forward port changelog
[tor.git] / src / common / container.c
blob4dc0a7ad77df0e31bd559b860f57254a8d4b4178
1 /* Copyright 2003-2004 Roger Dingledine; Copyright 2004 Nick Mathewson */
2 /* See LICENSE for licensing information */
3 /* $Id$ */
4 const char container_c_id[] = "$Id$";
6 #include "compat.h"
7 #include "util.h"
8 #include "log.h"
9 #include "../or/tree.h"
10 #include "container.h"
12 #ifdef HAVE_CTYPE_H
13 #include <ctype.h>
14 #endif
15 #include <stdlib.h>
16 #include <string.h>
17 #include <assert.h>
19 /* =====
20 * smartlist_t: a simple resizeable array abstraction.
21 * ===== */
23 /* All newly allocated smartlists have this capacity.
25 #define SMARTLIST_DEFAULT_CAPACITY 32
27 #ifndef FAST_SMARTLIST
28 struct smartlist_t {
29 /** <b>list</b> has enough capacity to store exactly <b>capacity</b> elements
30 * before it needs to be resized. Only the first <b>num_used</b> (\<=
31 * capacity) elements point to valid data.
33 void **list;
34 int num_used;
35 int capacity;
37 #endif
39 /** Allocate and return an empty smartlist.
41 smartlist_t *smartlist_create() {
42 smartlist_t *sl = tor_malloc(sizeof(smartlist_t));
43 sl->num_used = 0;
44 sl->capacity = SMARTLIST_DEFAULT_CAPACITY;
45 sl->list = tor_malloc(sizeof(void *) * sl->capacity);
46 return sl;
49 /** Deallocate a smartlist. Does not release storage associated with the
50 * list's elements.
52 void smartlist_free(smartlist_t *sl) {
53 free(sl->list);
54 free(sl);
57 /** Change the capacity of the smartlist to <b>n</b>, so that we can grow
58 * the list up to <b>n</b> elements with no further reallocation or wasted
59 * space. If <b>n</b> is less than or equal to the number of elements
60 * currently in the list, reduce the list's capacity as much as
61 * possible without losing elements.
63 void smartlist_set_capacity(smartlist_t *sl, int n) {
64 if (n < sl->num_used)
65 n = sl->num_used;
66 if (sl->capacity != n) {
67 sl->capacity = n;
68 sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
72 /** Remove all elements from the list.
74 void smartlist_clear(smartlist_t *sl) {
75 sl->num_used = 0;
78 /** Set the list's new length to <b>len</b> (which must be \<= the list's
79 * current size). Remove the last smartlist_len(sl)-len elements from the
80 * list.
82 void smartlist_truncate(smartlist_t *sl, int len)
84 tor_assert(len <= sl->num_used);
85 sl->num_used = len;
88 /** Append element to the end of the list. */
89 void smartlist_add(smartlist_t *sl, void *element) {
90 if (sl->num_used >= sl->capacity) {
91 sl->capacity *= 2;
92 sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
94 sl->list[sl->num_used++] = element;
97 /** Append each element from S2 to the end of S1. */
98 void smartlist_add_all(smartlist_t *sl, const smartlist_t *s2)
100 SMARTLIST_FOREACH(s2, void *, element, smartlist_add(sl, element));
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
105 * rearranged.
107 void smartlist_remove(smartlist_t *sl, void *element) {
108 int i;
109 if (element == NULL)
110 return;
111 for (i=0; i < sl->num_used; i++)
112 if (sl->list[i] == element) {
113 sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
114 i--; /* so we process the new i'th element */
118 /** Return true iff some element E of sl has E==element.
120 int smartlist_isin(const smartlist_t *sl, void *element) {
121 int i;
122 for (i=0; i < sl->num_used; i++)
123 if (sl->list[i] == element)
124 return 1;
125 return 0;
128 int smartlist_string_isin(const smartlist_t *sl, const char *element) {
129 int i;
130 for (i=0; i < sl->num_used; i++)
131 if (strcmp((const char*)sl->list[i],element)==0)
132 return 1;
133 return 0;
136 int smartlist_string_num_isin(const smartlist_t *sl, int num) {
137 char buf[16];
138 tor_snprintf(buf,sizeof(buf),"%d", num);
139 return smartlist_string_isin(sl, buf);
142 /** Return true iff some element E of sl2 has smartlist_isin(sl1,E).
144 int smartlist_overlap(const smartlist_t *sl1, const smartlist_t *sl2) {
145 int i;
146 for (i=0; i < sl2->num_used; i++)
147 if (smartlist_isin(sl1, sl2->list[i]))
148 return 1;
149 return 0;
152 /** Remove every element E of sl1 such that !smartlist_isin(sl2,E).
153 * Does not preserve the order of sl1.
155 void smartlist_intersect(smartlist_t *sl1, const smartlist_t *sl2) {
156 int i;
157 for (i=0; i < sl1->num_used; i++)
158 if (!smartlist_isin(sl2, sl1->list[i])) {
159 sl1->list[i] = sl1->list[--sl1->num_used]; /* swap with the end */
160 i--; /* so we process the new i'th element */
164 /** Remove every element E of sl1 such that smartlist_isin(sl2,E).
165 * Does not preserve the order of sl1.
167 void smartlist_subtract(smartlist_t *sl1, const smartlist_t *sl2) {
168 int i;
169 for (i=0; i < sl2->num_used; i++)
170 smartlist_remove(sl1, sl2->list[i]);
173 #ifndef FAST_SMARTLIST
174 /** Return the <b>idx</b>th element of sl.
176 void *smartlist_get(const smartlist_t *sl, int idx)
178 tor_assert(sl);
179 tor_assert(idx>=0);
180 tor_assert(idx < sl->num_used);
181 return sl->list[idx];
183 /** Change the value of the <b>idx</b>th element of sl to <b>val</b>.
185 void smartlist_set(smartlist_t *sl, int idx, void *val)
187 tor_assert(sl);
188 tor_assert(idx>=0);
189 tor_assert(idx < sl->num_used);
190 sl->list[idx] = val;
192 /** Return the number of items in sl.
194 int smartlist_len(const smartlist_t *sl)
196 return sl->num_used;
198 #endif
200 /** Remove the <b>idx</b>th element of sl; if idx is not the last
201 * element, swap the last element of sl into the <b>idx</b>th space.
202 * Return the old value of the <b>idx</b>th element.
204 void smartlist_del(smartlist_t *sl, int idx)
206 tor_assert(sl);
207 tor_assert(idx>=0);
208 tor_assert(idx < sl->num_used);
209 sl->list[idx] = sl->list[--sl->num_used];
211 /** Remove the <b>idx</b>th element of sl; if idx is not the last element,
212 * moving all subsequent elements back one space. Return the old value
213 * of the <b>idx</b>th element.
215 void smartlist_del_keeporder(smartlist_t *sl, int idx)
217 tor_assert(sl);
218 tor_assert(idx>=0);
219 tor_assert(idx < sl->num_used);
220 --sl->num_used;
221 if (idx < sl->num_used)
222 memmove(sl->list+idx, sl->list+idx+1, sizeof(void*)*(sl->num_used-idx));
224 /** Insert the value <b>val</b> as the new <b>idx</b>th element of
225 * <b>sl</b>, moving all items previously at <b>idx</b> or later
226 * forward one space.
228 void smartlist_insert(smartlist_t *sl, int idx, void *val)
230 tor_assert(sl);
231 tor_assert(idx>=0);
232 tor_assert(idx <= sl->num_used);
233 if (idx == sl->num_used) {
234 smartlist_add(sl, val);
235 } else {
236 /* Ensure sufficient capacity */
237 if (sl->num_used >= sl->capacity) {
238 sl->capacity *= 2;
239 sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
241 /* Move other elements away */
242 if (idx < sl->num_used)
243 memmove(sl->list + idx + 1, sl->list + idx,
244 sizeof(void*)*(sl->num_used-idx));
245 sl->num_used++;
246 sl->list[idx] = val;
251 * Split a string <b>str</b> along all occurrences of <b>sep</b>,
252 * adding the split strings, in order, to <b>sl</b>. If
253 * <b>flags</b>&amp;SPLIT_SKIP_SPACE is true, remove initial and
254 * trailing space from each entry. If
255 * <b>flags</b>&amp;SPLIT_IGNORE_BLANK is true, remove any entries of
256 * length 0. If max>0, divide the string into no more than <b>max</b>
257 * pieces. If <b>sep</b> is NULL, split on any sequence of horizontal space.
259 int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep,
260 int flags, int max)
262 const char *cp, *end, *next;
263 int n = 0;
265 tor_assert(sl);
266 tor_assert(str);
268 cp = str;
269 while (1) {
270 if (flags&SPLIT_SKIP_SPACE) {
271 while (TOR_ISSPACE(*cp)) ++cp;
274 if (max>0 && n == max-1) {
275 end = strchr(cp,'\0');
276 } else if (sep) {
277 end = strstr(cp,sep);
278 if (!end)
279 end = strchr(cp,'\0');
280 } else {
281 for (end = cp; *end && *end != '\t' && *end != ' '; ++end)
285 if (!*end) {
286 next = NULL;
287 } else if (sep) {
288 next = end+strlen(sep);
289 } else {
290 next = end+1;
291 while (*next == '\t' || *next == ' ')
292 ++next;
295 if (flags&SPLIT_SKIP_SPACE) {
296 while (end > cp && TOR_ISSPACE(*(end-1)))
297 --end;
299 if (end != cp || !(flags&SPLIT_IGNORE_BLANK)) {
300 smartlist_add(sl, tor_strndup(cp, end-cp));
301 ++n;
303 if (!next)
304 break;
305 cp = next;
308 return n;
311 /** Allocate and return a new string containing the concatenation of
312 * the elements of <b>sl</b>, in order, separated by <b>join</b>. If
313 * <b>terminate</b> is true, also terminate the string with <b>join</b>.
314 * If <b>len_out</b> is not NULL, set <b>len_out</b> to the length of
315 * the returned string. Requires that every element of <b>sl</b> is
316 * NUL-terminated string.
318 char *smartlist_join_strings(smartlist_t *sl, const char *join,
319 int terminate, size_t *len_out)
321 return smartlist_join_strings2(sl,join,strlen(join),terminate,len_out);
324 /** As smartlist_join_strings, but instead of separating/terminated with a
325 * NUL-terminated string <b>join</b>, uses the <b>join_len</b>-byte sequence
326 * at <b>join</b>. (Useful for generating a sequence of NUL-terminated
327 * strings.)
329 char *smartlist_join_strings2(smartlist_t *sl, const char *join,
330 size_t join_len, int terminate, size_t *len_out)
332 int i;
333 size_t n = 0;
334 char *r = NULL, *dst, *src;
336 tor_assert(sl);
337 tor_assert(join);
338 join_len = strlen(join);
339 for (i = 0; i < sl->num_used; ++i) {
340 n += strlen(sl->list[i]);
341 n += join_len;
343 if (!terminate) n -= join_len;
344 dst = r = tor_malloc(n+1);
345 for (i = 0; i < sl->num_used; ) {
346 for (src = sl->list[i]; *src; )
347 *dst++ = *src++;
348 if (++i < sl->num_used || terminate) {
349 memcpy(dst, join, join_len);
350 dst += join_len;
353 *dst = '\0';
355 if (len_out)
356 *len_out = dst-r;
357 return r;
360 /* Splay-tree implementation of string-to-void* map
362 struct strmap_entry_t {
363 SPLAY_ENTRY(strmap_entry_t) node;
364 char *key;
365 void *val;
368 struct strmap_t {
369 SPLAY_HEAD(strmap_tree, strmap_entry_t) head;
372 static int compare_strmap_entries(struct strmap_entry_t *a,
373 struct strmap_entry_t *b)
375 return strcmp(a->key, b->key);
378 SPLAY_PROTOTYPE(strmap_tree, strmap_entry_t, node, compare_strmap_entries);
379 SPLAY_GENERATE(strmap_tree, strmap_entry_t, node, compare_strmap_entries);
381 /** Create a new empty map from strings to void*'s.
383 strmap_t* strmap_new(void)
385 strmap_t *result;
386 result = tor_malloc(sizeof(strmap_t));
387 SPLAY_INIT(&result->head);
388 return result;
391 /** Set the current value for <b>key</b> to <b>val</b>. Returns the previous
392 * value for <b>key</b> if one was set, or NULL if one was not.
394 * This function makes a copy of <b>key</b> if necessary, but not of <b>val</b>.
396 void* strmap_set(strmap_t *map, const char *key, void *val)
398 strmap_entry_t *resolve;
399 strmap_entry_t search;
400 void *oldval;
401 tor_assert(map);
402 tor_assert(key);
403 tor_assert(val);
404 search.key = (char*)key;
405 resolve = SPLAY_FIND(strmap_tree, &map->head, &search);
406 if (resolve) {
407 oldval = resolve->val;
408 resolve->val = val;
409 return oldval;
410 } else {
411 resolve = tor_malloc_zero(sizeof(strmap_entry_t));
412 resolve->key = tor_strdup(key);
413 resolve->val = val;
414 SPLAY_INSERT(strmap_tree, &map->head, resolve);
415 return NULL;
419 /** Return the current value associated with <b>key</b>, or NULL if no
420 * value is set.
422 void* strmap_get(strmap_t *map, const char *key)
424 strmap_entry_t *resolve;
425 strmap_entry_t search;
426 tor_assert(map);
427 tor_assert(key);
428 search.key = (char*)key;
429 resolve = SPLAY_FIND(strmap_tree, &map->head, &search);
430 if (resolve) {
431 return resolve->val;
432 } else {
433 return NULL;
437 /** Remove the value currently associated with <b>key</b> from the map.
438 * Return the value if one was set, or NULL if there was no entry for
439 * <b>key</b>.
441 * Note: you must free any storage associated with the returned value.
443 void* strmap_remove(strmap_t *map, const char *key)
445 strmap_entry_t *resolve;
446 strmap_entry_t search;
447 void *oldval;
448 tor_assert(map);
449 tor_assert(key);
450 search.key = (char*)key;
451 resolve = SPLAY_FIND(strmap_tree, &map->head, &search);
452 if (resolve) {
453 oldval = resolve->val;
454 SPLAY_REMOVE(strmap_tree, &map->head, resolve);
455 tor_free(resolve->key);
456 tor_free(resolve);
457 return oldval;
458 } else {
459 return NULL;
463 /** Same as strmap_set, but first converts <b>key</b> to lowercase. */
464 void* strmap_set_lc(strmap_t *map, const char *key, void *val)
466 /* We could be a little faster by using strcasecmp instead, and a separate
467 * type, but I don't think it matters. */
468 void *v;
469 char *lc_key = tor_strdup(key);
470 tor_strlower(lc_key);
471 v = strmap_set(map,lc_key,val);
472 tor_free(lc_key);
473 return v;
475 /** Same as strmap_get, but first converts <b>key</b> to lowercase. */
476 void* strmap_get_lc(strmap_t *map, const char *key)
478 void *v;
479 char *lc_key = tor_strdup(key);
480 tor_strlower(lc_key);
481 v = strmap_get(map,lc_key);
482 tor_free(lc_key);
483 return v;
485 /** Same as strmap_remove, but first converts <b>key</b> to lowercase */
486 void* strmap_remove_lc(strmap_t *map, const char *key)
488 void *v;
489 char *lc_key = tor_strdup(key);
490 tor_strlower(lc_key);
491 v = strmap_remove(map,lc_key);
492 tor_free(lc_key);
493 return v;
496 /** Invoke fn() on every entry of the map, in order. For every entry,
497 * fn() is invoked with that entry's key, that entry's value, and the
498 * value of <b>data</b> supplied to strmap_foreach. fn() must return a new
499 * (possibly unmodified) value for each entry: if fn() returns NULL, the
500 * entry is removed.
502 * Example:
503 * \code
504 * static void* upcase_and_remove_empty_vals(const char *key, void *val,
505 * void* data) {
506 * char *cp = (char*)val;
507 * if (!*cp) { // val is an empty string.
508 * free(val);
509 * return NULL;
510 * } else {
511 * for (; *cp; cp++)
512 * *cp = toupper(*cp);
514 * return val;
518 * ...
520 * strmap_foreach(map, upcase_and_remove_empty_vals, NULL);
521 * \endcode
523 void strmap_foreach(strmap_t *map,
524 void* (*fn)(const char *key, void *val, void *data),
525 void *data)
527 strmap_entry_t *ptr, *next;
528 tor_assert(map);
529 tor_assert(fn);
530 for (ptr = SPLAY_MIN(strmap_tree, &map->head); ptr != NULL; ptr = next) {
531 /* This remove-in-place usage is specifically blessed in tree(3). */
532 next = SPLAY_NEXT(strmap_tree, &map->head, ptr);
533 ptr->val = fn(ptr->key, ptr->val, data);
534 if (!ptr->val) {
535 SPLAY_REMOVE(strmap_tree, &map->head, ptr);
536 tor_free(ptr->key);
537 tor_free(ptr);
542 /** return an <b>iterator</b> pointer to the front of a map.
544 * Iterator example:
546 * \code
547 * // uppercase values in "map", removing empty values.
549 * strmap_iter_t *iter;
550 * const char *key;
551 * void *val;
552 * char *cp;
554 * for (iter = strmap_iter_init(map); !strmap_iter_done(iter); ) {
555 * strmap_iter_get(iter, &key, &val);
556 * cp = (char*)val;
557 * if (!*cp) {
558 * iter = strmap_iter_next_rmv(iter);
559 * free(val);
560 * } else {
561 * for (;*cp;cp++) *cp = toupper(*cp);
562 * iter = strmap_iter_next(iter);
565 * \endcode
568 strmap_iter_t *strmap_iter_init(strmap_t *map)
570 tor_assert(map);
571 return SPLAY_MIN(strmap_tree, &map->head);
573 /** Advance the iterator <b>iter</b> for map a single step to the next entry.
575 strmap_iter_t *strmap_iter_next(strmap_t *map, strmap_iter_t *iter)
577 tor_assert(map);
578 tor_assert(iter);
579 return SPLAY_NEXT(strmap_tree, &map->head, iter);
581 /** Advance the iterator <b>iter</b> a single step to the next entry, removing
582 * the current entry.
584 strmap_iter_t *strmap_iter_next_rmv(strmap_t *map, strmap_iter_t *iter)
586 strmap_iter_t *next;
587 tor_assert(map);
588 tor_assert(iter);
589 next = SPLAY_NEXT(strmap_tree, &map->head, iter);
590 SPLAY_REMOVE(strmap_tree, &map->head, iter);
591 tor_free(iter->key);
592 tor_free(iter);
593 return next;
595 /** Set *keyp and *valp to the current entry pointed to by iter.
597 void strmap_iter_get(strmap_iter_t *iter, const char **keyp, void **valp)
599 tor_assert(iter);
600 tor_assert(keyp);
601 tor_assert(valp);
602 *keyp = iter->key;
603 *valp = iter->val;
605 /** Return true iff iter has advanced past the last entry of map.
607 int strmap_iter_done(strmap_iter_t *iter)
609 return iter == NULL;
611 /** Remove all entries from <b>map</b>, and deallocate storage for those entries.
612 * If free_val is provided, it is invoked on every value in <b>map</b>.
614 void
615 strmap_free(strmap_t *map, void (*free_val)(void*))
617 strmap_entry_t *ent, *next;
618 for (ent = SPLAY_MIN(strmap_tree, &map->head); ent != NULL; ent = next) {
619 next = SPLAY_NEXT(strmap_tree, &map->head, ent);
620 SPLAY_REMOVE(strmap_tree, &map->head, ent);
621 tor_free(ent->key);
622 if (free_val)
623 tor_free(ent->val);
625 tor_assert(SPLAY_EMPTY(&map->head));
626 tor_free(map);
629 int strmap_isempty(strmap_t *map)
631 return SPLAY_EMPTY(&map->head);