getCSVFromVector: optimize and add tests
Optimization: avoid copy; simpifiled unnessary branches; reduced
temperary string being created when doing string concatenation.
Added unit test for this function.
Tested: unit test
Signed-off-by: Nan Zhou <nanzhoumails@gmail.com>
Change-Id: I8c334dc4f087e262bb3e8613e86cfc2a93d525a0
diff --git a/user_mgr.cpp b/user_mgr.cpp
index 95fb421..7ee424d 100644
--- a/user_mgr.cpp
+++ b/user_mgr.cpp
@@ -44,6 +44,10 @@
#include <fstream>
#include <numeric>
#include <regex>
+#include <span>
+#include <string>
+#include <string_view>
+#include <vector>
namespace phosphor
{
@@ -130,29 +134,18 @@
return stdOutput;
}
-static std::string getCSVFromVector(std::vector<std::string> vec)
+std::string getCSVFromVector(std::span<const std::string> vec)
{
- switch (vec.size())
+ if (vec.empty())
{
- case 0:
- {
- return "";
- }
- break;
-
- case 1:
- {
- return std::string{vec[0]};
- }
- break;
-
- default:
- {
- return std::accumulate(
- std::next(vec.begin()), vec.end(), vec[0],
- [](std::string a, std::string b) { return a + ',' + b; });
- }
+ return "";
}
+ return std::accumulate(std::next(vec.begin()), vec.end(), vec[0],
+ [](std::string&& val, std::string_view element) {
+ val += ',';
+ val += element;
+ return val;
+ });
}
static bool removeStringFromCSV(std::string& csvStr, const std::string& delStr)