Skip to content

Commit

Permalink
Implement stringutils::join_arguments. (#1524)
Browse files Browse the repository at this point in the history
Co-authored-by: Nicolas Cornu <[email protected]>
  • Loading branch information
1uc and Nicolas Cornu authored Oct 21, 2024
1 parent b200275 commit 8438f61
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/utils/string_utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
6 changes: 6 additions & 0 deletions src/utils/string_utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions test/unit/utils/string_utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
}

0 comments on commit 8438f61

Please sign in to comment.