Debian Codegraph @

LspCpp/third_party/uri/src/detail/uri_resolve.cpp

raw
1 // Copyright 2013-2016 Glyn Matthews.
2 // Copyright 2013 Hannes Kamecke.
3 // Distributed under the Boost Software License, Version 1.0.
4 // (See accompanying file LICENSE_1_0.txt or copy at
5 // http://www.boost.org/LICENSE_1_0.txt)
6
7 #include "uri_resolve.hpp"
8 #include "algorithm_find.hpp"
9
10 using namespace network::algorithm;
11 using network::uri;
12 using network::string_view;
13 namespace network_detail = network::detail;
14
15 namespace {
16
17 // remove_dot_segments
18 inline void remove_last_segment(std::string &path) {
19 while (!path.empty()) {
20 if (path.back() == '/') {
21 path.pop_back();
22 break;
23 }
24 path.pop_back();
25 }
26 }
27
28 inline bool starts_with(std::string const &str, const char *range) {
29 return str.find(range) == 0;
30 }
31
32 // implementation of http://tools.ietf.org/html/rfc3986#section-5.2.4
33 static std::string remove_dot_segments(std::string input) {
34 std::string result;
35
36 while (!input.empty()) {
37 if (starts_with(input, "../")) {
38 input.erase(0, 3);
39 } else if (starts_with(input, "./")) {
40 input.erase(0, 2);
41 } else if (starts_with(input, "/./")) {
42 input.erase(0, 2);
43 input.front() = '/';
44 } else if (input == "/.") {
45 input.erase(0, 1);
46 input.front() = '/';
47 } else if (starts_with(input, "/../")) {
48 input.erase(0, 3);
49 remove_last_segment(result);
50 } else if (starts_with(input, "/..")) {
51 input.erase(0, 2);
52 input.front() = '/';
53 remove_last_segment(result);
54 } else if (all(input, [](char ch) { return ch == '.'; })) {
55 input.clear();
56 } else {
57 int n = (input.front() == '/') ? 1 : 0;
58 std::string::iterator slash = find_nth(input, '/', n);
59 result.append(std::begin(input), slash);
60 input.erase(std::begin(input), slash);
61 }
62 }
63 return result;
64 }
65
66 } // namespace
67
68 std::string network_detail::remove_dot_segments(string_view path) {
69 return ::remove_dot_segments(path.to_string());
70 }
71
72 // implementation of http://tools.ietf.org/html/rfc3986#section-5.2.3
73 std::string network_detail::merge_paths(const uri &base, const uri &reference) {
74 std::string result;
75
76 if (!base.has_path() || base.path().empty()) {
77 result = "/";
78 } else {
79 const auto &base_path = base.path();
80 auto last_slash = algorithm::find_last(base_path, '/');
81 if (last_slash != base_path.cend()) ++last_slash;
82 result.append(std::begin(base_path), last_slash);
83 }
84 if (reference.has_path()) {
85 result.append(reference.path().to_string());
86 }
87 return remove_dot_segments(string_view(result));
88 }