Bladeren bron

Basic string-join functionality

svn:r2521
Nick Mathewson 21 jaren geleden
bovenliggende
commit
c5964d6738
3 gewijzigde bestanden met toevoegingen van 46 en 0 verwijderingen
  1. 26 0
      src/common/util.c
  2. 1 0
      src/common/util.h
  3. 19 0
      src/or/test.c

+ 26 - 0
src/common/util.c

@@ -609,6 +609,32 @@ int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep,
   return n;
 }
 
+char *smartlist_join_strings(smartlist_t *sl, const char *join, int terminate)
+{
+  int i;
+  size_t n = 0, jlen;
+  char *r = NULL, *dst, *src;
+  
+  tor_assert(sl && join);
+  jlen = strlen(join);
+  for (i = 0; i < sl->num_used; ++i) {
+    n += strlen(sl->list[i]);
+    n += jlen;
+  }
+  if (!terminate) n -= jlen;
+  dst = r = tor_malloc(n+1);
+  for (i = 0; i < sl->num_used; ) {
+    for (src = sl->list[i]; *src; )
+      *dst++ = *src++;
+    if (++i < sl->num_used || terminate) {
+      memcpy(dst, join, jlen);
+      dst += jlen;
+    }
+  }
+  *dst = '\0';
+  return r;
+}
+
 /* Splay-tree implementation of string-to-void* map
  */
 struct strmap_entry_t {

+ 1 - 0
src/common/util.h

@@ -145,6 +145,7 @@ int smartlist_len(const smartlist_t *sl);
 #define SPLIT_IGNORE_BLANK 0x02
 int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep,
                            int flags, int max);
+char *smartlist_join_strings(smartlist_t *sl, const char *join, int terminate);
 
 #define SMARTLIST_FOREACH(sl, type, var, cmd)                   \
   do {                                                          \

+ 19 - 0
src/or/test.c

@@ -581,6 +581,22 @@ test_util() {
   test_streq("a", smartlist_get(sl, 1));
   test_streq("bc", smartlist_get(sl, 2));
   test_streq("", smartlist_get(sl, 3));
+  cp = smartlist_join_strings(sl, "", 0);
+  test_streq(cp, "abcabc");
+  tor_free(cp);
+  cp = smartlist_join_strings(sl, "!", 0);
+  test_streq(cp, "abc!a!bc!");
+  tor_free(cp);
+  cp = smartlist_join_strings(sl, "XY", 0);
+  test_streq(cp, "abcXYaXYbcXY");
+  tor_free(cp);
+  cp = smartlist_join_strings(sl, "XY", 1);
+  test_streq(cp, "abcXYaXYbcXYXY");
+  tor_free(cp);
+  cp = smartlist_join_strings(sl, "", 1);
+  test_streq(cp, "abcabc");
+  tor_free(cp);
+
   smartlist_split_string(sl, "/def/  /ghijk", "/", 0, 0);
   test_eq(8, smartlist_len(sl));
   test_streq("", smartlist_get(sl, 4));
@@ -615,6 +631,9 @@ test_util() {
   test_eq(5, smartlist_len(sl));
   test_streq("z", smartlist_get(sl, 3));
   test_streq("zhasd <>  <> bnud<>", smartlist_get(sl, 4));
+  SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
+  smartlist_clear(sl);
+  
 
   /* Test tor_strstrip() */
   strcpy(buf, "Testing 1 2 3");