nix-util: Add concatMapStrings
(cherry picked from commit 583a852c8a6b7461dad3635337a7d2fe6f205fd3) Change-Id: I38e9174d800339cae26bcdbebb0e27008a96839e
This commit is contained in:
+17
-1
@@ -5,6 +5,7 @@
|
||||
#include "lix/libutil/types.hh"
|
||||
|
||||
#include <vector>
|
||||
#include <boost/container/small_vector.hpp>
|
||||
|
||||
namespace nix {
|
||||
|
||||
@@ -34,7 +35,6 @@ MakeError(FormatError, Error);
|
||||
*/
|
||||
template<class C> C tokenizeString(std::string_view s, std::string_view separators = " \t\n\r");
|
||||
|
||||
|
||||
/**
|
||||
* Concatenate the given strings with a separator between the
|
||||
* elements.
|
||||
@@ -63,6 +63,22 @@ auto concatStrings(Parts && ... parts)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Apply a function to the `iterable`'s items and concat them with `separator`.
|
||||
*/
|
||||
template<class C, class F>
|
||||
std::string concatMapStringsSep(std::string_view separator, const C & iterable, F fn)
|
||||
{
|
||||
boost::container::small_vector<std::string, 64> strings;
|
||||
strings.reserve(iterable.size());
|
||||
for (const auto & elem : iterable) {
|
||||
strings.push_back(fn(elem));
|
||||
}
|
||||
return concatStringsSep(separator, strings);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Add quotes around a collection of strings.
|
||||
*/
|
||||
|
||||
@@ -667,4 +667,43 @@ namespace nix {
|
||||
ASSERT_EQ(filterANSIEscapes("f𐍈𐍈bär", true, 4), "f𐍈𐍈b");
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------------------
|
||||
* concatMapStringsSep
|
||||
* --------------------------------------------------------------------------*/
|
||||
TEST(concatMapStringsSep, empty)
|
||||
{
|
||||
Strings strings;
|
||||
|
||||
ASSERT_EQ(concatMapStringsSep(",", strings, [](const std::string & s) { return s; }), "");
|
||||
}
|
||||
|
||||
TEST(concatMapStringsSep, justOne)
|
||||
{
|
||||
Strings strings;
|
||||
strings.push_back("this");
|
||||
|
||||
ASSERT_EQ(concatMapStringsSep(",", strings, [](const std::string & s) { return s; }), "this");
|
||||
}
|
||||
|
||||
TEST(concatMapStringsSep, two)
|
||||
{
|
||||
Strings strings;
|
||||
strings.push_back("this");
|
||||
strings.push_back("that");
|
||||
|
||||
ASSERT_EQ(concatMapStringsSep(",", strings, [](const std::string & s) { return s; }), "this,that");
|
||||
}
|
||||
|
||||
TEST(concatMapStringsSep, map)
|
||||
{
|
||||
std::map<std::string, std::string> strings;
|
||||
strings["this"] = "that";
|
||||
strings["1"] = "one";
|
||||
|
||||
ASSERT_EQ(
|
||||
concatMapStringsSep(
|
||||
", ", strings, [](const std::pair<std::string, std::string> & s) { return s.first + " -> " + s.second; }),
|
||||
"1 -> one, this -> that");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user