diff --git a/src/espstrutils.cpp b/src/espstrutils.cpp index db750fb..70b4dde 100644 --- a/src/espstrutils.cpp +++ b/src/espstrutils.cpp @@ -95,4 +95,27 @@ std::string toHexString(std::basic_string_view buf) return hex; } +tl::expected, std::string> fromHexString(std::string_view str) +{ + const auto binMaxLen = (str.size()+1)/2; + uint8_t binBuf[binMaxLen]; + + size_t binLen; + if (const auto result = sodium_hex2bin(binBuf, binMaxLen, str.data(), str.size(), NULL, &binLen, NULL); result != 0) + { + ESP_LOGW(TAG, "sodium_hex2bin() failed with %i", result); + return tl::make_unexpected(fmt::format("sodium_hex2bin() failed with {}", result)); + } + + if (binLen != str.size() / 2) + { + ESP_LOGW(TAG, "invalid hex"); + return tl::make_unexpected("invalid hex"); + } + + const std::basic_string_view bin{binBuf, binLen}; + + return bin; +} + } // namespace espcpputils diff --git a/src/espstrutils.h b/src/espstrutils.h index a0e75a7..fce121c 100644 --- a/src/espstrutils.h +++ b/src/espstrutils.h @@ -4,6 +4,9 @@ #include #include +// 3rdparty lib includes +#include + // esp-idf includes #include #include @@ -21,4 +24,10 @@ inline std::string toHexString(std::string_view str) return toHexString(std::basic_string_view{reinterpret_cast(str.data()), str.size()}); } +tl::expected, std::string> fromHexString(std::string_view str); +inline tl::expected, std::string> fromHexString(std::basic_string_view str) +{ + return fromHexString(std::string_view{reinterpret_cast(str.data()), str.size()}); +} + } // namespace espcpputils