aboutsummaryrefslogtreecommitdiff
path: root/src/stringutils.cpp
diff options
context:
space:
mode:
authorGravatar Sadie Powell2024-01-13 17:45:42 +0000
committerGravatar Sadie Powell2024-01-13 17:45:42 +0000
commit0086b162aa6c4b4f9ed98ff7c9f2f31dbe039944 (patch)
treef6be9230e8f28ce1371b3a2a0dc9570e6a00c09d /src/stringutils.cpp
parentFix the string overload of Hex::Encode not passing on the separator. (diff)
Add Hex::Decode as a complement for Hex::Encode.
Diffstat (limited to 'src/stringutils.cpp')
-rw-r--r--src/stringutils.cpp26
1 files changed, 26 insertions, 0 deletions
diff --git a/src/stringutils.cpp b/src/stringutils.cpp
index 7162a104e..d5a28a3e1 100644
--- a/src/stringutils.cpp
+++ b/src/stringutils.cpp
@@ -113,6 +113,32 @@ std::string Hex::Encode(const void* data, size_t length, const char* table, char
return buffer;
}
+std::string Hex::Decode(const void* data, size_t length, const char* table, char separator)
+{
+ if (!table)
+ table = Hex::TABLE_LOWER;
+
+ // The size of each hex segment.
+ size_t segment = (separator ? 3 : 2);
+
+ // Preallocate the output buffer to avoid constant reallocations.
+ std::string buffer;
+ buffer.reserve(length / segment);
+
+ const char* cdata = static_cast<const char*>(data);
+ for (size_t idx = 0; idx + 1 < length; idx += segment)
+ {
+ // Attempt to find the octets in the table.
+ const char* table1 = strchr(table, cdata[idx]);
+ const char* table2 = strchr(table, cdata[idx + 1]);
+
+ char pair = ((table1 ? table1 - table : 0) << 4) + (table2 ? table2 - table : 0);
+ buffer.push_back(pair);
+ }
+
+ return buffer;
+}
+
std::string Base64::Encode(const void* data, size_t length, const char* table, char padding)
{
// Use the default table if one is not specified.