From 2f52861c20c795d9e35f6af09b6cb5ad1dc6f2dc Mon Sep 17 00:00:00 2001 From: levlam Date: Mon, 2 Sep 2019 16:49:18 +0300 Subject: [PATCH] Add hex_encode. GitOrigin-RevId: f5b42ce196f463d9d5cdb4536ee7b829f198583b --- tdutils/td/utils/misc.cpp | 45 ++++++++++++++++++++++++--------------- tdutils/td/utils/misc.h | 4 +++- 2 files changed, 31 insertions(+), 18 deletions(-) diff --git a/tdutils/td/utils/misc.cpp b/tdutils/td/utils/misc.cpp index 6c823139b..f4c5e4f0c 100644 --- a/tdutils/td/utils/misc.cpp +++ b/tdutils/td/utils/misc.cpp @@ -98,21 +98,32 @@ Result hex_decode(Slice hex) { return std::move(result); } +string hex_encode(Slice data) { + const char *hex = "0123456789abcdef"; + string res; + res.reserve(2 * data.size()); + for (unsigned char c : data) { + res.push_back(hex[c >> 4]); + res.push_back(hex[c & 15]); + } + return res; +} + static bool is_url_char(char c) { return is_alnum(c) || c == '-' || c == '.' || c == '_' || c == '~'; } -string url_encode(Slice str) { - size_t length = 3 * str.size(); - for (auto c : str) { +string url_encode(Slice data) { + size_t length = 3 * data.size(); + for (auto c : data) { length -= 2 * is_url_char(c); } - if (length == str.size()) { - return str.str(); + if (length == data.size()) { + return data.str(); } string result; result.reserve(length); - for (auto c : str) { + for (auto c : data) { if (is_url_char(c)) { result += c; } else { @@ -126,6 +137,17 @@ string url_encode(Slice str) { return result; } +string buffer_to_hex(Slice buffer) { + const char *hex = "0123456789ABCDEF"; + string res(2 * buffer.size(), '\0'); + for (std::size_t i = 0; i < buffer.size(); i++) { + auto c = buffer.ubegin()[i]; + res[2 * i] = hex[c & 15]; + res[2 * i + 1] = hex[c >> 4]; + } + return res; +} + namespace { template @@ -169,17 +191,6 @@ bool is_zero_or_one(unsigned char c) { } // namespace -string buffer_to_hex(Slice buffer) { - const char *hex = "0123456789ABCDEF"; - string res(2 * buffer.size(), '\0'); - for (std::size_t i = 0; i < buffer.size(); i++) { - auto c = buffer.ubegin()[i]; - res[2 * i] = hex[c & 15]; - res[2 * i + 1] = hex[c >> 4]; - } - return res; -} - std::string zero_encode(Slice data) { return x_encode(data, is_zero); } diff --git a/tdutils/td/utils/misc.h b/tdutils/td/utils/misc.h index b11749ce3..50ac0a456 100644 --- a/tdutils/td/utils/misc.h +++ b/tdutils/td/utils/misc.h @@ -303,7 +303,9 @@ T clamp(T value, T min_value, T max_value) { Result hex_decode(Slice hex); -string url_encode(Slice str); +string hex_encode(Slice data); + +string url_encode(Slice data); // run-time checked narrowing cast (type conversion):