| 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 |
#include "uri_normalize.hpp" |
| 7 |
#include "uri_percent_encode.hpp" |
| 8 |
#include "algorithm.hpp" |
| 9 |
#include "algorithm_split.hpp" |
| 10 |
#include <iterator> |
| 11 |
#include <vector> |
| 12 |
|
| 13 |
using namespace network::algorithm; |
| 14 |
using network::string_view; |
| 15 |
using network::uri_comparison_level; |
| 16 |
namespace network_detail = network::detail; |
| 17 |
|
| 18 |
std::string network_detail::normalize_path_segments(string_view path) { |
| 19 |
std::string result; |
| 20 |
|
| 21 |
if (!path.empty()) { |
| 22 |
std::vector<std::string> path_segments; |
| 23 |
split(path_segments, path, '/'); |
| 24 |
|
| 25 |
bool last_segment_is_slash = path_segments.back().empty(); |
| 26 |
std::vector<std::string> normalized_segments; |
| 27 |
for (const auto &segment : path_segments) { |
| 28 |
if (segment.empty() || (segment == ".")) { |
| 29 |
continue; |
| 30 |
} else if (segment == "..") { |
| 31 |
if (normalized_segments.empty()) { |
| 32 |
throw uri_builder_error(); |
| 33 |
} |
| 34 |
normalized_segments.pop_back(); |
| 35 |
} else { |
| 36 |
normalized_segments.push_back(segment); |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
for (const auto &segment : normalized_segments) { |
| 41 |
result += "/" + segment; |
| 42 |
} |
| 43 |
|
| 44 |
if (last_segment_is_slash) { |
| 45 |
result += "/"; |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
if (result.empty()) { |
| 50 |
result = "/"; |
| 51 |
} |
| 52 |
|
| 53 |
return result; |
| 54 |
} |
| 55 |
|
| 56 |
std::string network_detail::normalize_path(string_view path, |
| 57 |
uri_comparison_level level) { |
| 58 |
auto result = path.to_string(); |
| 59 |
|
| 60 |
if (uri_comparison_level::syntax_based == level) { |
| 61 |
// case normalization |
| 62 |
for_each(result, percent_encoded_to_upper<std::string>()); |
| 63 |
|
| 64 |
// % encoding normalization |
| 65 |
result.erase(detail::decode_encoded_unreserved_chars(std::begin(result), |
| 66 |
std::end(result)), |
| 67 |
std::end(result)); |
| 68 |
|
| 69 |
// % path segment normalization |
| 70 |
result = normalize_path_segments(result); |
| 71 |
} |
| 72 |
|
| 73 |
return result; |
| 74 |
} |