Kurlyk
Loading...
Searching...
No Matches
percent_encoding.hpp
Go to the documentation of this file.
1#pragma once
2#ifndef _KURLYK_UTILS_PERCENT_ENCODING_HPP_INCLUDED
3#define _KURLYK_UTILS_PERCENT_ENCODING_HPP_INCLUDED
4
11
12namespace kurlyk::utils {
13
17 std::string percent_encode(const std::string &value) noexcept {
18 static const char hex_chars[] = "0123456789ABCDEF";
19
20 std::string result;
21 result.reserve(value.size()); // Reserve minimum required size
22
23 for (auto &chr : value) {
24 if (isalnum(static_cast<unsigned char>(chr)) || chr == '-' || chr == '.' || chr == '_' || chr == '~') {
25 result += chr;
26 } else {
27 result += '%';
28 result += hex_chars[static_cast<unsigned char>(chr) >> 4];
29 result += hex_chars[static_cast<unsigned char>(chr) & 0x0F];
30 }
31 }
32
33 return result;
34 }
35
39 std::string percent_decode(const std::string &value) noexcept {
40 std::string result;
41 result.reserve(value.size() / 3 + (value.size() % 3)); // Reserve minimum required size
42
43 for (std::size_t i = 0; i < value.size(); ++i) {
44 if (value[i] == '%' && i + 2 < value.size()) {
45 char hex[] = { value[i + 1], value[i + 2], '\0' };
46 char decoded_chr = static_cast<char>(std::strtol(hex, nullptr, 16));
47 result += decoded_chr;
48 i += 2;
49 } else if (value[i] == '+') {
50 result += ' ';
51 } else {
52 result += value[i];
53 }
54 }
55
56 return result;
57 }
58
59} // namespace kurlyk::utils
60
61#endif
std::string percent_decode(const std::string &value) noexcept
Decodes a Percent-Encoded string.
std::string percent_encode(const std::string &value) noexcept
Encodes a string using Percent Encoding according to RFC 3986.