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