diff --git a/src/utils/string_utils.cpp b/src/utils/string_utils.cpp index 51947eebd..e804817a8 100644 --- a/src/utils/string_utils.cpp +++ b/src/utils/string_utils.cpp @@ -27,5 +27,16 @@ std::string to_string(double value, const std::string& format_spec) { return fmt::format(format_spec, value); } +std::string join_arguments(const std::string& lhs, const std::string& rhs) { + if (lhs.empty()) { + return rhs; + } else if (rhs.empty()) { + return lhs; + } else { + return fmt::format("{}", fmt::join({lhs, rhs}, ", ")); + } +} + + } // namespace stringutils } // namespace nmodl diff --git a/src/utils/string_utils.hpp b/src/utils/string_utils.hpp index 2b0d81d12..5099550d6 100644 --- a/src/utils/string_utils.hpp +++ b/src/utils/string_utils.hpp @@ -210,6 +210,12 @@ static inline bool starts_with(const std::string& haystack, const std::string& n */ std::string to_string(double value, const std::string& format_spec = "{:.16g}"); +/** Joint two (list of) arguments. + * + * The tricks is to not add a ',' when either side is empty. + */ +std::string join_arguments(const std::string& lhs, const std::string& rhs); + /** \} */ // end of utils } // namespace stringutils diff --git a/test/unit/utils/string_utils.cpp b/test/unit/utils/string_utils.cpp index e55631fc3..1d4bf3b62 100644 --- a/test/unit/utils/string_utils.cpp +++ b/test/unit/utils/string_utils.cpp @@ -54,3 +54,21 @@ TEST_CASE("starts_with") { REQUIRE(!stringutils::starts_with("abcde", "abcde++")); } } + +TEST_CASE("join_arguments") { + SECTION("both empty") { + REQUIRE(stringutils::join_arguments("", "") == ""); + } + + SECTION("lhs emtpy") { + REQUIRE(stringutils::join_arguments("", "foo, bar") == "foo, bar"); + } + + SECTION("rhs empty") { + REQUIRE(stringutils::join_arguments("foo", "") == "foo"); + } + + SECTION("neither empty") { + REQUIRE(stringutils::join_arguments("foo", "bar") == "foo, bar"); + } +}