Skip to content

Expose path and query parser #150

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions include/skyr/v2/core/parse_path.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright 2020 Glyn Matthews.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef SKYR_V2_CORE_PARSE_QUERY_HPP
#define SKYR_V2_CORE_PARSE_QUERY_HPP

#include <string>
#include <vector>
#include <skyr/v2/core/parse.hpp>

namespace skyr::inline v2 {
///
/// \param path
/// \param validation_error
/// \return
inline auto parse_path(
std::string_view path, bool *validation_error) -> tl::expected<std::vector<std::string>, url_parse_errc> {
auto url = details::basic_parse(path, validation_error, nullptr, nullptr, url_parse_state::path_start);
if (url) {
return url.value().path;
}
return tl::make_unexpected(url.error());
}

///
/// \param path
/// \return
inline auto parse_path(
std::string_view path) -> tl::expected<std::vector<std::string>, url_parse_errc> {
[[maybe_unused]] bool validation_error = false;
return parse_path(path, &validation_error);
}
} // namespace skyr::inline v2

#endif // SKYR_V2_CORE_PARSE_QUERY_HPP
85 changes: 85 additions & 0 deletions include/skyr/v2/core/parse_query.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// Copyright 2020 Glyn Matthews.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef SKYR_V2_CORE_PARSE_QUERY_HPP
#define SKYR_V2_CORE_PARSE_QUERY_HPP

#include <string>
#include <vector>
#include <range/v3/view/split_when.hpp>
#include <range/v3/view/transform.hpp>
#include <skyr/v2/core/parse.hpp>
#include <skyr/v2/percent_encoding/percent_decode.hpp>

namespace skyr::inline v2 {
///
struct query_parameter {
std::string name;
std::optional<std::string> value;

/// Constructor
query_parameter() = default;

/// Constructor
/// \param name The parameter name
query_parameter(std::string name) : name(std::move(name)) {}

/// Constructor
/// \param name The parameter name
/// \param value The parameter value
query_parameter(std::string name, std::string value) : name(std::move(name)), value(std::move(value)) {}
};

///
/// \param query
/// \param validation_error
/// \return
inline auto parse_query(
std::string_view query, bool *validation_error) -> tl::expected<std::vector<query_parameter>, url_parse_errc> {
if (!query.empty() && (query.front() == '?')) {
query.remove_prefix(1);
}

auto url = details::basic_parse(query, validation_error, nullptr, nullptr, url_parse_state::query);
if (url) {
static constexpr auto is_separator = [](auto c) { return c == '&' || c == ';'; };

static constexpr auto to_nvp = [](auto &&param) -> query_parameter {
if (ranges::empty(param)) {
return {};
}

auto element = std::string_view(std::addressof(*std::begin(param)), ranges::distance(param));
auto delim = element.find_first_of('=');
if (delim != std::string_view::npos) {
return {std::string(element.substr(0, delim)), std::string(element.substr(delim + 1))};
} else {
return {std::string(element)};
}
};

std::vector<query_parameter> parameters{};
if (url.value().query) {
for (auto &&parameter :
url.value().query.value() | ranges::views::split_when(is_separator) | ranges::views::transform(to_nvp)) {
parameters.emplace_back(parameter);
}
}
return parameters;
}
return tl::make_unexpected(url.error());
}

///
/// \param query
/// \return
inline auto parse_query(
std::string_view query) -> tl::expected<std::vector<query_parameter>, url_parse_errc> {
[[maybe_unused]] bool validation_error = false;
return parse_query(query, &validation_error);
}
} // namespace skyr::inline v2

#endif // SKYR_V2_CORE_PARSE_QUERY_HPP
11 changes: 7 additions & 4 deletions include/skyr/v2/core/serialize.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,18 @@ inline auto serialize_file_scheme(const url_record &url) -> std::string {
return (!url.host && (url.scheme == "file")) ? "//" : "";
}

inline auto serialize_host(const url_record &url) -> std::string {
inline auto serialize_authority(const url_record &url) -> std::string {
return url.host
? fmt::format("//{}{}{}", serialize_credentials(url), url.host.value().serialize(), serialize_port(url))
: serialize_file_scheme(url);
}

inline auto serialize_path(const std::vector<std::string> &path) -> std::string {
return fmt::format("/{}", path | ranges::views::join('/') | ranges::to<std::string>());
}

inline auto serialize_path(const url_record &url) -> std::string {
return url.cannot_be_a_base_url ? url.path.front()
: fmt::format("/{}", url.path | ranges::views::join('/') | ranges::to<std::string>());
return url.cannot_be_a_base_url ? url.path.front() : serialize_path(url.path);
}

inline auto serialize_query(const url_record &url) -> std::string {
Expand All @@ -54,7 +57,7 @@ inline auto serialize_fragment(const url_record &url) -> std::string {
/// \param url A URL record
/// \returns A serialized URL string, excluding the fragment
inline auto serialize_excluding_fragment(const url_record &url) -> url_record::string_type {
return fmt::format("{}:{}{}{}", url.scheme, details::serialize_host(url), details::serialize_path(url),
return fmt::format("{}:{}{}{}", url.scheme, details::serialize_authority(url), details::serialize_path(url),
details::serialize_query(url));
}

Expand Down
26 changes: 13 additions & 13 deletions include/skyr/v2/core/url_parser_context.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -236,19 +236,10 @@ class url_parser_context {
buffer.push_back(lower);
} else if (byte == ':') {
if (state_override) {
if (url.is_special() && !is_special(buffer)) {
return tl::make_unexpected(url_parse_errc::cannot_override_scheme);
}

if (!url.is_special() && is_special(buffer)) {
return tl::make_unexpected(url_parse_errc::cannot_override_scheme);
}

if ((url.includes_credentials() || url.port) && (buffer == "file")) {
return tl::make_unexpected(url_parse_errc::cannot_override_scheme);
}

if ((url.scheme == "file") && (!url.host || url.host.value().is_empty())) {
if ((url.is_special() && !is_special(buffer)) ||
(!url.is_special() && is_special(buffer)) ||
((url.includes_credentials() || url.port) && (buffer == "file")) ||
((url.scheme == "file") && (!url.host || url.host.value().is_empty()))) {
return tl::make_unexpected(url_parse_errc::cannot_override_scheme);
}
}
Expand Down Expand Up @@ -895,11 +886,17 @@ class url_parser_context {
}

void pct_encode_and_append_to_query(char byte) {
if (!url.query) {
set_empty_query();
}
auto pct_encoded = percent_encode_byte(std::byte(byte), percent_encoding::encode_set::none);
url.query.value() += std::move(pct_encoded).to_string();
}

void append_to_query(char byte) {
if (!url.query) {
set_empty_query();
}
url.query.value().push_back(byte);
}

Expand All @@ -908,6 +905,9 @@ class url_parser_context {
}

void append_to_fragment(char byte) {
if (!url.fragment) {
set_empty_fragment();
}
auto pct_encoded = percent_encode_byte(std::byte(byte), percent_encoding::encode_set::fragment);
url.fragment.value() += pct_encoded.to_string();
}
Expand Down
84 changes: 29 additions & 55 deletions include/skyr/v2/json/json.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
#include <optional>
#include <vector>
#include <tl/expected.hpp>
#include <range/v3/view/split_when.hpp>
#include <range/v3/view/transform.hpp>
#include <nlohmann/json.hpp>
#include <fmt/format.h>
#include <skyr/v2/core/parse_query.hpp>
#include <skyr/v2/percent_encoding/percent_encode.hpp>
#include <skyr/v2/percent_encoding/percent_decode.hpp>

Expand All @@ -28,78 +28,52 @@ inline auto encode_query(const nlohmann::json &json, char separator='&', char eq
-> tl::expected<std::string, json_errc> {
using namespace std::string_literals;

auto result = ""s;
std::string result{};

if (!json.is_object()) {
return tl::make_unexpected(json_errc::invalid_query);
}

for (auto &[key, value] : json.items()) {

if (value.is_string()) {
result += percent_encode(key);
result += equal;
result += percent_encode(value.get<std::string>());
result += separator;
}
else if (value.is_array()) {
result += fmt::format(
"{}{}{}{}", percent_encode(key), equal, percent_encode(value.get<std::string>()), separator);
} else if (value.is_array()) {
for (auto &element : value.items()) {
result += percent_encode(key);
result += equal;
result += percent_encode(element.value().get<std::string>());
result += separator;
result += fmt::format(
"{}{}{}{}", percent_encode(key), equal, percent_encode(element.value().get<std::string>()), separator);
}
}
else {
result += percent_encode(key);
result += equal;
result += separator;
} else {
result += fmt::format("{}{}{}", percent_encode(key), equal, separator);
}
}

return result.substr(0, result.size() - 1);
}

inline auto decode_query(std::string_view query, char separator='&', char equal='=') -> nlohmann::json {
if (query[0] == '?') {
query.remove_prefix(1);
}

static constexpr auto is_separator = [] (auto &&c) {
return c == '&' || c == ';';
};

static constexpr auto to_nvp = [] (auto &&param) -> std::pair<std::string_view, std::optional<std::string_view>> {
auto element = std::string_view(std::addressof(*std::begin(param)), ranges::distance(param));
auto delim = element.find_first_of("=");
if (delim != std::string_view::npos) {
return { element.substr(0, delim), element.substr(delim + 1) };
}
else {
return { element, std::nullopt };
}
};

inline auto decode_query(std::string_view query) -> nlohmann::json {
nlohmann::json object;
for (auto [name, value] : query | ranges::views::split_when(is_separator) | ranges::views::transform(to_nvp)) {
const auto name_ = skyr::percent_decode(name).value();
const auto value_ = value? skyr::percent_decode(value.value()).value() : std::string();

if (object.contains(name_)) {
auto current_value = object[name_];
if (current_value.is_string()) {
auto prev_value = current_value.get<std::string>();
object[name_] = std::vector<std::string>{prev_value, value_};
}
else if (current_value.is_array()) {
auto values = current_value.get<std::vector<std::string>>();
values.emplace_back(value_);
object[name_] = values;
auto parameters = parse_query(query);
if (parameters) {
for (auto &&[name, value] : parameters.value()) {
const auto name_ = skyr::percent_decode(name).value();
const auto value_ = value ? skyr::percent_decode(value.value()).value() : std::string();

if (object.contains(name_)) {
auto current_value = object[name_];
if (current_value.is_string()) {
auto prev_value = current_value.get<std::string>();
object[name_] = std::vector<std::string>{prev_value, value_};
} else if (current_value.is_array()) {
auto values = current_value.get<std::vector<std::string>>();
values.emplace_back(value_);
object[name_] = values;
}
} else {
object[name_] = value_;
}
}
else {
object[name_] = value_;
}
}
return object;
}
Expand Down
4 changes: 2 additions & 2 deletions include/skyr/v2/platform/endianness.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ requires std::is_integral_v<intT> constexpr inline auto swap_endianness(intT v)
} // namespace details

template <class intT>
requires std::is_integral_v<intT> constexpr inline auto to_network_byte_order(intT v) noexcept {
requires std::is_integral_v<intT> constexpr inline auto to_network_byte_order(intT v) noexcept -> intT {
return (std::endian::big == std::endian::native) ? v : details::swap_endianness(v); // NOLINT
}

template <class intT>
requires std::is_integral_v<intT> constexpr inline auto from_network_byte_order(intT v) noexcept {
requires std::is_integral_v<intT> constexpr inline auto from_network_byte_order(intT v) noexcept -> intT {
return (std::endian::big == std::endian::native) ? v : details::swap_endianness(v); // NOLINT
}
} // namespace skyr::inline v2
Expand Down
Loading