From: Philippe Proulx Date: Fri, 10 May 2024 19:32:10 +0000 (-0400) Subject: Add bt2c::join() X-Git-Url: http://drtracing.org/?a=commitdiff_plain;h=6875eb64630a6d722fdd8336d4282d56a240dcd0;p=babeltrace.git Add bt2c::join() 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 { "salut", "meow", "mix" }, ", ") << '\n'; } will print salut, meow, mix Signed-off-by: Philippe Proulx Change-Id: Id3ff90cf3b2fa4336b71860dbe3c0dff83668607 Reviewed-on: https://review.lttng.org/c/babeltrace/+/12735 --- diff --git a/src/Makefile.am b/src/Makefile.am index 314b7bae..383f9778 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -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 index 00000000..0989f6d3 --- /dev/null +++ b/src/cpp-common/bt2c/join.hpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2024 Philippe Proulx + * + * SPDX-License-Identifier: MIT + */ + +#ifndef BABELTRACE_CPP_COMMON_BT2C_JOIN_HPP +#define BABELTRACE_CPP_COMMON_BT2C_JOIN_HPP + +#include +#include + +#include "cpp-common/bt2s/string-view.hpp" + +namespace bt2c { +namespace internal { + +template +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 +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 */