util: Add a MacAddr population function
This one is pretty trivial since there is only one size of mac
address, but we want to be sure we validate the buffer.
Tested:
Built and runs through unit tests. Works when integrated into
neighbor parsing code.
Change-Id: Iaf58fc398b51a3bcbbf70968cbe353beeb7b9f54
Signed-off-by: William A. Kennington III <wak@google.com>
diff --git a/test/test_util.cpp b/test/test_util.cpp
index 0e58081..4e39821 100644
--- a/test/test_util.cpp
+++ b/test/test_util.cpp
@@ -31,6 +31,19 @@
EXPECT_EQ('4', mac_address::internal::toHex(std::byte(4)));
}
+TEST_F(TestUtil, MacFromBuf)
+{
+ std::string tooSmall(1, 'a');
+ std::string tooLarge(24, 'a');
+ std::string buf{'\x00', '\xde', '\xad', '\x00', '\xbe', '\xef'};
+
+ MacAddr mac = mac_address::fromBuf(buf);
+ EXPECT_EQ(0, memcmp(buf.data(), mac.data(), buf.size()));
+
+ EXPECT_THROW(mac_address::fromBuf(tooSmall), std::runtime_error);
+ EXPECT_THROW(mac_address::fromBuf(tooLarge), std::runtime_error);
+}
+
TEST_F(TestUtil, MacToString)
{
MacAddr mac1{
diff --git a/util.cpp b/util.cpp
index b1300fb..d1bcc71 100644
--- a/util.cpp
+++ b/util.cpp
@@ -603,6 +603,17 @@
return sdbusplus::message::variant_ns::get<std::string>(value);
}
+MacAddr fromBuf(std::string_view buf)
+{
+ MacAddr ret;
+ if (buf.size() != ret.size())
+ {
+ throw std::runtime_error("Invalid MacAddr size");
+ }
+ memcpy(ret.data(), buf.data(), ret.size());
+ return ret;
+}
+
std::string toString(const MacAddr& mac)
{
std::string str;
diff --git a/util.hpp b/util.hpp
index a07fa49..9531d4f 100644
--- a/util.hpp
+++ b/util.hpp
@@ -49,6 +49,11 @@
*/
std::string getfromInventory(sdbusplus::bus::bus& bus);
+/* @brief Marshalls the bytes for a mac address into a MacAddr.
+ * @param[in] buf - The network byte order address
+ */
+MacAddr fromBuf(std::string_view buf);
+
/** @brief Converts the given mac address bytes into a string
* @param[in] bytes - The mac address
* @returns A valid mac address string