common: Add helper function toString
Add helper function to convert variable_field to std::string.
Tested: Unit tests passed
Signed-off-by: Tom Joseph <rushtotom@gmail.com>
Change-Id: Ide0e50f2dc89e051d7a958a54773f5cb94e70e40
diff --git a/common/test/pldm_utils_test.cpp b/common/test/pldm_utils_test.cpp
index a65b33b..006d065 100644
--- a/common/test/pldm_utils_test.cpp
+++ b/common/test/pldm_utils_test.cpp
@@ -906,3 +906,28 @@
pldm_pdr_destroy(repo);
}
+
+TEST(toString, allTestCases)
+{
+ variable_field buffer{};
+ constexpr std::string_view str1{};
+ auto returnStr1 = toString(buffer);
+ EXPECT_EQ(returnStr1, str1);
+
+ constexpr std::string_view str2{"0penBmc"};
+ constexpr std::array<uint8_t, 7> bufferArr1{0x30, 0x70, 0x65, 0x6e,
+ 0x42, 0x6d, 0x63};
+ buffer.ptr = bufferArr1.data();
+ buffer.length = bufferArr1.size();
+ auto returnStr2 = toString(buffer);
+ EXPECT_EQ(returnStr2, str2);
+
+ constexpr std::string_view str3{"0pen mc"};
+ // \xa0 - the non-breaking space in ISO-8859-1
+ constexpr std::array<uint8_t, 7> bufferArr2{0x30, 0x70, 0x65, 0x6e,
+ 0xa0, 0x6d, 0x63};
+ buffer.ptr = bufferArr2.data();
+ buffer.length = bufferArr2.size();
+ auto returnStr3 = toString(buffer);
+ EXPECT_EQ(returnStr3, str3);
+}
\ No newline at end of file
diff --git a/common/utils.cpp b/common/utils.cpp
index 964c04f..97fc1dd 100644
--- a/common/utils.cpp
+++ b/common/utils.cpp
@@ -5,7 +5,9 @@
#include <xyz/openbmc_project/Common/error.hpp>
+#include <algorithm>
#include <array>
+#include <cctype>
#include <ctime>
#include <fstream>
#include <iostream>
@@ -503,5 +505,18 @@
}
}
+std::string toString(const struct variable_field& var)
+{
+ if (var.ptr == nullptr || !var.length)
+ {
+ return "";
+ }
+
+ std::string str(reinterpret_cast<const char*>(var.ptr), var.length);
+ std::replace_if(
+ str.begin(), str.end(), [](const char& c) { return !isprint(c); }, ' ');
+ return str;
+}
+
} // namespace utils
} // namespace pldm
diff --git a/common/utils.hpp b/common/utils.hpp
index 710282c..101fd49 100644
--- a/common/utils.hpp
+++ b/common/utils.hpp
@@ -3,6 +3,7 @@
#include "libpldm/base.h"
#include "libpldm/bios.h"
#include "libpldm/platform.h"
+#include "libpldm/utils.h"
#include "types.hpp"
@@ -350,5 +351,16 @@
*/
void printBuffer(const std::vector<uint8_t>& buffer, bool pldmVerbose);
+/** @brief Convert the buffer to std::string
+ *
+ * If there are characters that are not printable characters, it is replaced
+ * with space(0x20).
+ *
+ * @param[in] var - pointer to data and length of the data
+ *
+ * @return std::string equivalent of variable field
+ */
+std::string toString(const struct variable_field& var);
+
} // namespace utils
} // namespace pldm