Add hex_encode.

GitOrigin-RevId: f5b42ce196f463d9d5cdb4536ee7b829f198583b
This commit is contained in:
levlam 2019-09-02 16:49:18 +03:00
parent 7ca14d0851
commit 2f52861c20
2 changed files with 31 additions and 18 deletions

View File

@ -98,21 +98,32 @@ Result<string> 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 <class F>
@ -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);
}

View File

@ -303,7 +303,9 @@ T clamp(T value, T min_value, T max_value) {
Result<string> 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):