Skip to content
Repos

DevPlaceApp

C++ 1.4 KB45 lines Opens in site

Directory Raw Download

#include "screens/notifications/UrlSyntax.hpp"

#include <cctype>
#include <cstring>

namespace dp {

std::string UrlSyntax::percentDecode(const std::string& in) {
  std::string out;
  for (std::size_t i = 0; i < in.size(); ++i) {
    if (in[i] == '%' && i + 2 < in.size() && std::isxdigit(static_cast<unsigned char>(in[i + 1])) &&
        std::isxdigit(static_cast<unsigned char>(in[i + 2]))) {
      out.push_back(static_cast<char>(std::stoi(in.substr(i + 1, 2), nullptr, 16)));
      i += 2;
    } else {
      out.push_back(in[i]);
    }
  }
  return out;
}

std::optional<UrlSyntax::Parts> UrlSyntax::parse(const std::string& url) {
  if (url.empty()) return std::nullopt;  // URL(string: "") is nil
  for (unsigned char c : url) {
    if (c <= 0x20 || c == 0x7F || std::strchr("<>\"{}|\\^`", c)) return std::nullopt;
  }
  Parts parts;
  std::string rest = url;
  if (auto hash = rest.find('#'); hash != std::string::npos) {
    parts.fragment = percentDecode(rest.substr(hash + 1));
    rest.resize(hash);
  }
  if (auto q = rest.find('?'); q != std::string::npos) {
    parts.query = rest.substr(q + 1);
    rest.resize(q);
  }
  if (auto scheme = rest.find("://"); scheme != std::string::npos) {
    const auto slash = rest.find('/', scheme + 3);
    rest = slash == std::string::npos ? "" : rest.substr(slash);
  }
  parts.path = percentDecode(rest);
  return parts;
}

}  // namespace dp
32.9ms