[ovs-dev] [PATCH 1/2] sset: New function sset_join().

Ben Pfaff blp at ovn.org
Wed Sep 18 14:32:51 UTC 2019


This will acquire its first user in an upcoming commit.

This function follows the pattern set by svec_join().

Signed-off-by: Ben Pfaff <blp at ovn.org>
---
 lib/sset.c | 31 +++++++++++++++++++++++++++++++
 lib/sset.h |  3 +++
 2 files changed, 34 insertions(+)

diff --git a/lib/sset.c b/lib/sset.c
index 3deb1f9de9be..b2e3f43ec91b 100644
--- a/lib/sset.c
+++ b/lib/sset.c
@@ -18,6 +18,7 @@
 
 #include "sset.h"
 
+#include "openvswitch/dynamic-string.h"
 #include "hash.h"
 
 static uint32_t
@@ -118,6 +119,36 @@ sset_from_delimited_string(struct sset *set, const char *s_,
     free(s);
 }
 
+/* Returns a malloc()'d string that consists of the concatenation of all of the
+ * strings in 'sset' in lexicographic order, each separated from the next by
+ * 'delimiter' and followed by 'terminator'.  For example:
+ *
+ *   sset_join(("a", "b", "c"), ", ", ".") -> "a, b, c."
+ *   sset_join(("xyzzy"),       ", ", ".") -> "xyzzy."
+ *   sset_join((""),            ", ", ".") -> "."
+ *
+ * The caller is responsible for freeing the returned string (with free()).
+ */
+char *
+sset_join(const struct sset *sset,
+          const char *delimiter, const char *terminator)
+{
+    struct ds s = DS_EMPTY_INITIALIZER;
+
+    const char **names = sset_sort(sset);
+    for (size_t i = 0; i < sset_count(sset); i++) {
+        if (i) {
+            ds_put_cstr(&s, delimiter);
+        }
+        ds_put_cstr(&s, names[i]);
+    }
+    free(names);
+
+    ds_put_cstr(&s, terminator);
+
+    return ds_steal_cstr(&s);
+}
+
 /* Returns true if 'set' contains no strings, false if it contains at least one
  * string. */
 bool
diff --git a/lib/sset.h b/lib/sset.h
index 768d0cf0a1f3..f0bb8b534496 100644
--- a/lib/sset.h
+++ b/lib/sset.h
@@ -43,8 +43,11 @@ void sset_clone(struct sset *, const struct sset *);
 void sset_swap(struct sset *, struct sset *);
 void sset_moved(struct sset *);
 
+/* String parsing and formatting. */
 void sset_from_delimited_string(struct sset *, const char *s,
                                 const char *delimiters);
+char *sset_join(const struct sset *,
+                const char *delimiter, const char *terminator);
 
 /* Count. */
 bool sset_is_empty(const struct sset *);
-- 
2.21.0



More information about the dev mailing list