| 1 |
// Copyright 2013-2016 Glyn Matthews. |
| 2 |
// Distributed under the Boost Software License, Version 1.0. |
| 3 |
// (See accompanying file LICENSE_1_0.txt or copy at |
| 4 |
// http://www.boost.org/LICENSE_1_0.txt) |
| 5 |
|
| 6 |
#ifndef NETWORK_DETAIL_URI_PERCENT_ENCODE_INC |
| 7 |
#define NETWORK_DETAIL_URI_PERCENT_ENCODE_INC |
| 8 |
|
| 9 |
#include <string> |
| 10 |
#include <vector> |
| 11 |
#include <locale> |
| 12 |
#include <network/optional.hpp> |
| 13 |
#include <network/uri/detail/decode.hpp> |
| 14 |
|
| 15 |
namespace network { |
| 16 |
namespace detail { |
| 17 |
|
| 18 |
inline optional<char> percent_encode(std::string::const_iterator it) { |
| 19 |
try { |
| 20 |
char output = '\0'; |
| 21 |
detail::decode_char(it, &output); |
| 22 |
return output; |
| 23 |
} catch (percent_decoding_error &) { |
| 24 |
return optional<char>(); |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
template <class String> |
| 29 |
struct percent_encoded_to_upper { |
| 30 |
percent_encoded_to_upper() : count(0) {} |
| 31 |
|
| 32 |
void operator()(typename String::value_type &c) { |
| 33 |
if (c == '%') { |
| 34 |
count = 2; |
| 35 |
} else if (count > 0) { |
| 36 |
c = std::toupper(c, std::locale()); |
| 37 |
--count; |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
unsigned count; |
| 42 |
}; |
| 43 |
|
| 44 |
template <class Iter> |
| 45 |
Iter decode_encoded_unreserved_chars(Iter first, Iter last) { |
| 46 |
// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" |
| 47 |
// clang-format off |
| 48 |
const auto is_unreserved = [](char c) { |
| 49 |
return std::isalnum(c, std::locale()) |
| 50 |
|| '-' == c |
| 51 |
|| '.' == c |
| 52 |
|| '_' == c |
| 53 |
|| '~' == c; |
| 54 |
}; |
| 55 |
// clang-format on |
| 56 |
|
| 57 |
auto it = first, it2 = first; |
| 58 |
while (it != last) { |
| 59 |
if (*it == '%') { |
| 60 |
const auto sfirst = it; |
| 61 |
const auto opt_char = percent_encode(sfirst); |
| 62 |
if (opt_char && is_unreserved(*opt_char)) { |
| 63 |
*it2 = *opt_char; |
| 64 |
++it; |
| 65 |
++it; |
| 66 |
} else { |
| 67 |
*it2 = *it; |
| 68 |
} |
| 69 |
} else { |
| 70 |
*it2 = *it; |
| 71 |
} |
| 72 |
++it; |
| 73 |
++it2; |
| 74 |
} |
| 75 |
return it2; |
| 76 |
} |
| 77 |
} // namespace detail |
| 78 |
} // namespace network |
| 79 |
|
| 80 |
#endif // NETWORK_DETAIL_URI_PERCENT_ENCODE_INC |