diff options
Diffstat (limited to 'Source/cmStringAlgorithms.h')
-rw-r--r-- | Source/cmStringAlgorithms.h | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/Source/cmStringAlgorithms.h b/Source/cmStringAlgorithms.h index 55a1e46..3d7f9b0 100644 --- a/Source/cmStringAlgorithms.h +++ b/Source/cmStringAlgorithms.h @@ -7,6 +7,8 @@ #include <cctype> #include <cstring> #include <initializer_list> +#include <iterator> +#include <numeric> #include <sstream> #include <string> #include <utility> @@ -77,6 +79,38 @@ std::string cmJoin(Range const& rng, cm::string_view separator) return os.str(); } +/** Generic function to join strings range with separator + * and initial leading string into a single string. + */ +template <typename Range> +std::string cmJoinStrings(Range const& rng, cm::string_view separator, + cm::string_view initial) +{ + if (rng.empty()) { + return { std::begin(initial), std::end(initial) }; + } + + std::string result; + result.reserve( + std::accumulate(std::begin(rng), std::end(rng), + initial.size() + (rng.size() - 1) * separator.size(), + [](std::size_t sum, const std::string& item) { + return sum + item.size(); + })); + result.append(std::begin(initial), std::end(initial)); + + auto begin = std::begin(rng); + auto end = std::end(rng); + result += *begin; + + for (++begin; begin != end; ++begin) { + result.append(std::begin(separator), std::end(separator)); + result += *begin; + } + + return result; +} + /** * Faster overloads for std::string ranges. * If @a initial is provided, it prepends the resulted string without |