Add bt2c::join()
authorPhilippe Proulx <eeppeliteloop@gmail.com>
Fri, 10 May 2024 19:32:10 +0000 (15:32 -0400)
committerSimon Marchi <simon.marchi@efficios.com>
Wed, 4 Sep 2024 19:05:14 +0000 (15:05 -0400)
This new function template joins the strings of some container with
some delimiter.

The container needs a forward iterator and its elements need the data()
and size() methods.

The container may be empty.

For example:

    int main()
    {
        std::cout << bt2c::join(std::vector<std::string> {
            "salut", "meow", "mix"
        }, ", ") << '\n';
    }

will print

    salut, meow, mix

Signed-off-by: Philippe Proulx <eeppeliteloop@gmail.com>
Change-Id: Id3ff90cf3b2fa4336b71860dbe3c0dff83668607
Reviewed-on: https://review.lttng.org/c/babeltrace/+/12735

src/Makefile.am
src/cpp-common/bt2c/join.hpp [new file with mode: 0644]

index 314b7bae1d3138b8a41cbde3c6e1c8718b3ae6a4..383f9778294420cadb0bb9506d61e17258f149da 100644 (file)
@@ -172,6 +172,7 @@ cpp_common_libcpp_common_la_SOURCES = \
        cpp-common/bt2c/file-utils.hpp \
        cpp-common/bt2c/fmt.hpp \
        cpp-common/bt2c/glib-up.hpp \
+       cpp-common/bt2c/join.hpp \
        cpp-common/bt2c/json-val.cpp \
        cpp-common/bt2c/json-val.hpp \
        cpp-common/bt2c/json-val-req.cpp \
diff --git a/src/cpp-common/bt2c/join.hpp b/src/cpp-common/bt2c/join.hpp
new file mode 100644 (file)
index 0000000..0989f6d
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2024 Philippe Proulx <pproulx@efficios.com>
+ *
+ * SPDX-License-Identifier: MIT
+ */
+
+#ifndef BABELTRACE_CPP_COMMON_BT2C_JOIN_HPP
+#define BABELTRACE_CPP_COMMON_BT2C_JOIN_HPP
+
+#include <sstream>
+#include <string>
+
+#include "cpp-common/bt2s/string-view.hpp"
+
+namespace bt2c {
+namespace internal {
+
+template <typename StrT>
+void appendStrToSs(std::ostringstream& ss, const StrT& str)
+{
+    ss.write(str.data(), str.size());
+}
+
+} /* namespace internal */
+
+/*
+ * Joins the strings of `container` with the delimiter `delim`.
+ *
+ * `ContainerT` needs a forward iterator and its elements need the
+ * data() and size() methods.
+ *
+ * `container` may be empty.
+ */
+template <typename ContainerT>
+std::string join(const ContainerT& container, const bt2s::string_view delim)
+{
+    if (container.empty()) {
+        /* No elements */
+        return {};
+    }
+
+    if (container.size() == 1) {
+        /* Single element */
+        return std::string {container.begin()->data(), container.begin()->size()};
+    }
+
+    /* Two or more elements */
+    std::ostringstream ss;
+    auto it = container.begin();
+
+    internal::appendStrToSs(ss, *it);
+    ++it;
+
+    for (; it != container.end(); ++it) {
+        internal::appendStrToSs(ss, delim);
+        internal::appendStrToSs(ss, *it);
+    }
+
+    return ss.str();
+}
+
+} /* namespace bt2c */
+
+#endif /* BABELTRACE_CPP_COMMON_BT2C_JOIN_HPP */
This page took 0.025468 seconds and 4 git commands to generate.