Added from hex converters
This commit is contained in:
@@ -95,4 +95,27 @@ std::string toHexString(std::basic_string_view<unsigned char> buf)
|
|||||||
return hex;
|
return hex;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tl::expected<std::basic_string_view<unsigned char>, 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<unsigned char> bin{binBuf, binLen};
|
||||||
|
|
||||||
|
return bin;
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace espcpputils
|
} // namespace espcpputils
|
||||||
|
@@ -4,6 +4,9 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
|
|
||||||
|
// 3rdparty lib includes
|
||||||
|
#include <tl/expected.hpp>
|
||||||
|
|
||||||
// esp-idf includes
|
// esp-idf includes
|
||||||
#include <esp_sntp.h>
|
#include <esp_sntp.h>
|
||||||
#include <esp_log.h>
|
#include <esp_log.h>
|
||||||
@@ -21,4 +24,10 @@ inline std::string toHexString(std::string_view str)
|
|||||||
return toHexString(std::basic_string_view<unsigned char>{reinterpret_cast<const unsigned char *>(str.data()), str.size()});
|
return toHexString(std::basic_string_view<unsigned char>{reinterpret_cast<const unsigned char *>(str.data()), str.size()});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tl::expected<std::basic_string_view<unsigned char>, std::string> fromHexString(std::string_view str);
|
||||||
|
inline tl::expected<std::basic_string_view<unsigned char>, std::string> fromHexString(std::basic_string_view<unsigned char> str)
|
||||||
|
{
|
||||||
|
return fromHexString(std::string_view{reinterpret_cast<const char *>(str.data()), str.size()});
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace espcpputils
|
} // namespace espcpputils
|
||||||
|
Reference in New Issue
Block a user