commit 00f98f9fe526f050e4ccb152c8a971c8ada1da97
parent d541fc96a29d7da4e3bca3213fe5aed514500f42
Author: Andrew Laack <andrew@laack.co>
Date: Mon, 21 Sep 2026 19:00:04 -0500
Rewriting in cpp. Setup basic uri handling, object models, and tests
Diffstat:
19 files changed, 1045 insertions(+), 0 deletions(-)
diff --git a/.gitignore b/.gitignore
@@ -0,0 +1 @@
+*.out
diff --git a/Makefile b/Makefile
@@ -0,0 +1,20 @@
+build:
+ g++ src/main.cpp src/link.cpp src/site.cpp src/utils.cpp src/gemini-client.cpp src/browser.cpp -lCatch2Main -lCatch2 -o browser.out
+
+install:
+ echo "Not implemented"
+
+clean:
+ echo "Not implemented"
+
+browser-test:
+ g++ tests/browser-test.cpp src/link.cpp src/browser.cpp src/site.cpp src/utils.cpp src/gemini-client.cpp -lCatch2Main -lCatch2 -o test.out
+ ./test.out
+ rm test.out
+
+fetch-test:
+ g++ tests/fetch-test.cpp src/link.cpp src/site.cpp src/utils.cpp src/gemini-client.cpp -lCatch2Main -lCatch2 -o test.out
+ ./test.out
+ rm test.out
+
+test: browser-test fetch-test
diff --git a/include/browser.hpp b/include/browser.hpp
@@ -0,0 +1,16 @@
+#pragma once
+
+#include <vector>
+#include "site.hpp"
+#include "link.hpp"
+
+class Browser {
+ private:
+ std::vector<Link*> siteHistory;
+ int previousIdx = -1;
+ Site* currentSite;
+ public:
+ Browser();
+ void goToSite(std::string url);
+ Site* getCurrentSite();
+};
diff --git a/include/errors.hpp b/include/errors.hpp
@@ -0,0 +1,17 @@
+#pragma once
+
+#include <stdexcept>
+
+class NotImplemented : public std::logic_error
+{
+public:
+ NotImplemented() : std::logic_error("Function not yet implemented") { };
+};
+
+
+class FileReadError : public std::invalid_argument
+{
+public:
+ FileReadError() : std::invalid_argument("Unable to read file") { };
+};
+
diff --git a/include/gemini-client.hpp b/include/gemini-client.hpp
@@ -0,0 +1,9 @@
+#pragma once
+
+#include "site.hpp"
+#include "link.hpp"
+
+class GeminiClient {
+ public:
+ Site* fetchSite(Link link);
+};
diff --git a/include/link.hpp b/include/link.hpp
@@ -0,0 +1,16 @@
+#pragma once
+
+#include <optional>
+#include <string>
+#include "../vendor/uri.hpp"
+
+class Link {
+ private:
+ uri linkDestination = uri("gemini://example.com");
+ std::optional<std::string> linkText;
+ uri parseDestination(std::string destination, std::optional<uri> prior);
+ public:
+ Link(std::string text, std::optional<uri> prior = std::nullopt);
+ uri getLinkDestination();
+ std::optional<std::string> getLinkText();
+};
diff --git a/include/site.hpp b/include/site.hpp
@@ -0,0 +1,14 @@
+#pragma once
+
+#include <cstdint>
+#include <string>
+
+class Site{
+ private:
+ std::string body;
+ std::string header;
+ public:
+ Site(std::string header, std::string body);
+ std::string getBody();
+ uint32_t getStatusCode();
+};
diff --git a/include/utils.hpp b/include/utils.hpp
@@ -0,0 +1,7 @@
+#pragma once
+#include <string>
+
+bool isPrefixed(std::string input, std::string prefix);
+std::string readFileToString(std::string filePath);
+bool isWhiteSpace(std::string& line, int idx);
+std::string truncateAfter(std::string input, char truncate);
diff --git a/src/browser.cpp b/src/browser.cpp
@@ -0,0 +1,42 @@
+#include "../include/browser.hpp"
+#include "../include/site.hpp"
+#include "../include/gemini-client.hpp"
+
+void Browser::goToSite(std::string url) {
+
+ Link* prior = nullptr;
+
+ if(siteHistory.size() > previousIdx && previousIdx >= 0) {
+ prior = siteHistory[previousIdx];
+ }
+
+ auto client = GeminiClient{};
+
+ Link* destination = nullptr;
+
+ if(prior == nullptr) {
+ destination = new Link{url};
+ } else {
+ destination = new Link{url,prior->getLinkDestination()};
+ }
+
+ // TODO: Will need to clean up
+ siteHistory.push_back(destination);
+ previousIdx += 1;
+
+ Site* site = client.fetchSite(*destination);
+
+ if(currentSite != nullptr) {
+ delete currentSite;
+ }
+
+ currentSite = site;
+}
+
+Browser::Browser() {
+ currentSite = nullptr;
+}
+
+Site* Browser::getCurrentSite() {
+ return currentSite;
+}
diff --git a/src/gemini-client.cpp b/src/gemini-client.cpp
@@ -0,0 +1,32 @@
+#include "../include/gemini-client.hpp"
+#include "../include/site.hpp"
+#include "../include/utils.hpp"
+#include "../include/errors.hpp"
+#include <iostream>
+
+Site* GeminiClient::fetchSite(Link link) {
+
+ std::string destination = link.getLinkDestination().to_string();
+
+ // TODO: Actually handle uris
+ if(isPrefixed(destination, "gemini://")) {
+ throw NotImplemented();
+ } else if (isPrefixed(destination, "file://")){
+
+ destination = destination.substr(7, destination.size() - 7);
+
+ std::string fileStr = "";
+
+ try {
+ fileStr = readFileToString(destination);
+ } catch (FileReadError e ) {
+ return new Site {"51 \r\n", ""};
+ }
+
+ // TODO: how should I discern file types?
+ return new Site {"20 text/gemini\r\n", fileStr};
+ } else {
+ throw NotImplemented();
+ }
+
+}
diff --git a/src/link.cpp b/src/link.cpp
@@ -0,0 +1,63 @@
+#include "../include/link.hpp"
+#include <iostream>
+#include <optional>
+#include <string>
+#include "../include/utils.hpp"
+#include "../vendor/uri.hpp"
+
+
+Link::Link(std::string text, std::optional<uri> prior) {
+
+ std::string afterPrefix = text;
+
+ if(text.substr(0,2) == "=>") {
+ afterPrefix = text.substr(2,text.size());
+ }
+
+ int highest = -1;
+
+ for(int i = 0; i < afterPrefix.size(); ++i) {
+ if(!(isWhiteSpace(afterPrefix, i))) {
+ break;
+ }
+ highest = i;
+ }
+
+ std::string afterWhite = afterPrefix.substr(highest+1, afterPrefix.size());
+
+ int nextWhite = std::min(afterWhite.find(' '), afterWhite.find('\t'));
+
+ if(nextWhite != -1) {
+
+ linkText = afterWhite.substr(nextWhite+1);
+
+ std::string destination = afterWhite.substr(0, nextWhite);
+
+ linkDestination = parseDestination(destination, prior);
+
+ } else {
+ linkDestination = parseDestination(afterWhite, prior);
+ }
+}
+
+uri Link::parseDestination(std::string destination, std::optional<uri> prior) {
+
+ // TODO: Not sure if this is right w/ how file paths work.
+ if(destination.find("://") == -1) {
+ if(prior != std::nullopt) {
+ // TODO: Handle port
+ std::string truncated = truncateAfter(prior->get_scheme() + "://" + prior->get_host() + "/" + prior->get_path(), '/');
+ destination = truncated + destination;
+ } else {
+ destination = "file://" + destination;
+ }
+ }
+ return uri{destination};
+}
+
+uri Link::getLinkDestination() {
+ return linkDestination;
+}
+std::optional<std::string> Link::getLinkText() {
+ return linkText;
+}
diff --git a/src/main.cpp b/src/main.cpp
@@ -0,0 +1,10 @@
+#include "../include/browser.hpp"
+#include "../include/site.hpp"
+#include "../include/link.hpp"
+#include <iostream>
+
+int main() {
+ Browser b{};
+ b.goToSite("tests/sites/basic.gmi");
+ b.goToSite("basic_2.gmi");
+}
diff --git a/src/site.cpp b/src/site.cpp
@@ -0,0 +1,16 @@
+#include "../include/site.hpp"
+#include <iostream>
+#include <string>
+
+Site::Site(std::string header, std::string body) {
+ this->body = body;
+ this->header = header;
+}
+
+std::string Site::getBody() {
+ return body;
+}
+uint32_t Site::getStatusCode() {
+ uint32_t statusCode = std::stoi(header.substr(0,2));
+ return statusCode;
+}
diff --git a/src/utils.cpp b/src/utils.cpp
@@ -0,0 +1,35 @@
+#include "../include/utils.hpp"
+#include "../include/errors.hpp"
+#include <cstddef>
+#include <cstdint>
+#include <fstream>
+#include <iostream>
+#include <sstream>
+#include <string>
+
+bool isPrefixed(std::string input, std::string prefix) {
+ return std::string(input).find(prefix) == 0;
+}
+
+std::string readFileToString(std::string filePath) {
+ auto in = std::ifstream(filePath);
+ if(in.fail()) {
+ throw FileReadError{};
+ }
+ std::ostringstream sstr;
+ sstr << in.rdbuf();
+ return sstr.str();
+}
+
+bool isWhiteSpace(std::string& line, int idx) {
+ return line[idx] == ' ' || line[idx] == '\t';
+}
+
+std::string truncateAfter(std::string input, char truncate) {
+ for(int i = input.size() - 1; i >= 0; --i) {
+ if(input[i] == truncate) {
+ return input.substr(0,i+1);
+ }
+ }
+ return input;
+}
diff --git a/tests/browser-test.cpp b/tests/browser-test.cpp
@@ -0,0 +1,15 @@
+#include <catch2/catch_test_macros.hpp>
+#include "../include/link.hpp"
+#include "../include/browser.hpp"
+#include "../include/utils.hpp"
+
+
+TEST_CASE( "Basic navigation" ) {
+
+ Browser b{};
+ b.goToSite("tests/sites/basic.gmi");
+ REQUIRE(b.getCurrentSite()->getBody() == readFileToString("tests/sites/basic.gmi"));
+ b.goToSite("basic_2.gmi");
+ REQUIRE(b.getCurrentSite()->getBody() == readFileToString("tests/sites/basic_2.gmi"));
+}
+
diff --git a/tests/fetch-test.cpp b/tests/fetch-test.cpp
@@ -0,0 +1,66 @@
+#include <catch2/catch_test_macros.hpp>
+#include "../include/utils.hpp"
+#include <filesystem>
+
+#include "../include/gemini-client.hpp"
+#include "../include/link.hpp"
+
+TEST_CASE( "Link constructors" ) {
+
+ auto l2 = Link{"=> basic_2.gmi Other Page!", uri{"file://tests/sites/basic.gmi"}};
+
+ REQUIRE("file://tests/sites/basic_2.gmi" == l2.getLinkDestination().to_string());
+ REQUIRE("Other Page!" == l2.getLinkText());
+}
+
+// this mostly exists in case utils.cpp is busted in some very obvious way.
+TEST_CASE("Local Sanity Client") {
+ auto client = GeminiClient {};
+ auto ln = Link{"=> tests/sites/basic_2.gmi"};
+ Site* s = client.fetchSite(ln);
+
+ std::string expectedSite =
+ "# Hello World 2\n"
+ "\n"
+ "This is basic_2.gmi!\n"
+ "\n"
+ "=> basic.gmi Back to the basics!\n";
+
+ REQUIRE(s->getBody() == expectedSite);
+ delete s;
+
+}
+
+TEST_CASE("Match on all .gmi files in tests/sites") {
+
+ auto client = GeminiClient {};
+
+ for(const auto& current: std::filesystem::directory_iterator("tests/sites")) {
+ auto ln = Link{"=> " + current.path().string()};
+ Site* s = client.fetchSite(ln);
+ std::string expectedSite = readFileToString(current.path().string());
+ REQUIRE(s->getBody() == expectedSite);
+ delete s;
+ }
+}
+
+TEST_CASE("Match status code on .gmi files in tests/sites") {
+
+ auto client = GeminiClient {};
+
+ for(const auto& current: std::filesystem::directory_iterator("tests/sites")) {
+ auto ln = Link{"=> " + current.path().string()};
+ Site* s = client.fetchSite(ln);
+ REQUIRE(s->getStatusCode() == 20);
+ delete s;
+ }
+}
+
+TEST_CASE("Match status code on missing .gmi files") {
+ auto client = GeminiClient {};
+ auto ln = Link{"=> tests/sites/this_file_doesnt_exist.gmi"};
+ Site* s = client.fetchSite(ln);
+ REQUIRE(s->getStatusCode() == 51);
+ delete s;
+}
+
diff --git a/tests/sites/basic.gmi b/tests/sites/basic.gmi
@@ -0,0 +1,5 @@
+# Hello World
+
+This is a simple gemtext site, hosted on the filesystem!!!
+
+=> basic_2.gmi Other Page!
diff --git a/tests/sites/basic_2.gmi b/tests/sites/basic_2.gmi
@@ -0,0 +1,5 @@
+# Hello World 2
+
+This is basic_2.gmi!
+
+=> basic.gmi Back to the basics!
diff --git a/vendor/uri.hpp b/vendor/uri.hpp
@@ -0,0 +1,656 @@
+// Copyright (C) 2015 Ben Lewis <benjf5+github@gmail.com>
+// Licensed under the MIT license.
+
+#pragma once
+#include <cctype>
+#include <map>
+#include <string>
+#include <stdexcept>
+#include <utility>
+
+class uri
+{
+ /* URIs are broadly divided into two categories: hierarchical and
+ * non-hierarchical. Both hierarchical URIs and non-hierarchical URIs have a
+ * few elements in common; all URIs have a scheme of one or more alphanumeric
+ * characters followed by a colon, and they all may optionally have a query
+ * component preceded by a question mark, and a fragment component preceded by
+ * an octothorpe (hash mark: '#'). The query consists of stanzas separated by
+ * either ampersands ('&') or semicolons (';') (but only one or the other),
+ * and each stanza consists of a key and an optional value; if the value
+ * exists, the key and value must be divided by an equals sign.
+ *
+ * The following is an example from Wikipedia of a hierarchical URI:
+ * scheme:[//[user:password@]domain[:port]][/]path[?query][#fragment]
+ */
+
+public:
+
+ enum class scheme_category
+ {
+ Hierarchical,
+ NonHierarchical
+ };
+
+ enum class component
+ {
+ Scheme,
+ Content,
+ Username,
+ Password,
+ Host,
+ Port,
+ Path,
+ Query,
+ Fragment
+ };
+
+ enum class query_argument_separator
+ {
+ ampersand,
+ semicolon
+ };
+
+ uri(char const *uri_text, scheme_category category = scheme_category::Hierarchical,
+ query_argument_separator separator = query_argument_separator::ampersand) :
+ m_category(category),
+ m_port(0),
+ m_path_is_rooted(false),
+ m_separator(separator)
+ {
+ setup(std::string(uri_text), category);
+ };
+
+ uri(std::string const &uri_text, scheme_category category = scheme_category::Hierarchical,
+ query_argument_separator separator = query_argument_separator::ampersand) :
+ m_category(category),
+ m_port(0),
+ m_path_is_rooted(false),
+ m_separator(separator)
+ {
+ setup(uri_text, category);
+ };
+
+ uri(std::map<component, std::string> const &components,
+ scheme_category category,
+ bool rooted_path,
+ query_argument_separator separator = query_argument_separator::ampersand) :
+ m_category(category),
+ m_path_is_rooted(rooted_path),
+ m_separator(separator)
+ {
+ if (components.count(component::Scheme))
+ {
+ if (components.at(component::Scheme).length() == 0)
+ {
+ throw std::invalid_argument("Scheme cannot be empty.");
+ }
+ m_scheme = components.at(component::Scheme);
+ }
+ else
+ {
+ throw std::invalid_argument("A URI must have a scheme.");
+ }
+
+ if (category == scheme_category::Hierarchical)
+ {
+ if (components.count(component::Content))
+ {
+ throw std::invalid_argument("The content component is only for use in non-hierarchical URIs.");
+ }
+
+ bool has_username = components.count(component::Username);
+ bool has_password = components.count(component::Password);
+ if (has_username && has_password)
+ {
+ m_username = components.at(component::Username);
+ m_password = components.at(component::Password);
+ }
+ else if ((has_username && !has_password) || (!has_username && has_password))
+ {
+ throw std::invalid_argument("If a username or password is supplied, both must be provided.");
+ }
+
+ if (components.count(component::Host))
+ {
+ m_host = components.at(component::Host);
+ }
+
+ if (components.count(component::Port))
+ {
+ m_port = std::stoul(components.at(component::Port));
+ }
+
+ if (components.count(component::Path))
+ {
+ m_path = components.at(component::Path);
+ }
+ else
+ {
+ throw std::invalid_argument("A path is required on a hierarchical URI, even an empty path.");
+ }
+ }
+ else
+ {
+ if (components.count(component::Username)
+ || components.count(component::Password)
+ || components.count(component::Host)
+ || components.count(component::Port)
+ || components.count(component::Path))
+ {
+ throw std::invalid_argument("None of the hierarchical components are allowed in a non-hierarchical URI.");
+ }
+
+ if (components.count(component::Content))
+ {
+ m_content = components.at(component::Content);
+ }
+ else
+ {
+ throw std::invalid_argument("Content is a required component for a non-hierarchical URI, even an empty string.");
+ }
+ }
+
+ if (components.count(component::Query))
+ {
+ m_query = components.at(component::Query);
+ }
+
+ if (components.count(component::Fragment))
+ {
+ m_fragment = components.at(component::Fragment);
+ }
+ }
+
+ uri(uri const &other, std::map<component, std::string> const &replacements) :
+ m_category(other.m_category),
+ m_path_is_rooted(other.m_path_is_rooted),
+ m_separator(other.m_separator)
+ {
+ m_scheme = (replacements.count(component::Scheme))
+ ? replacements.at(component::Scheme) : other.m_scheme;
+
+ m_username = (replacements.count(component::Username))
+ ? replacements.at(component::Username) : other.m_username;
+
+ m_password = (replacements.count(component::Password))
+ ? replacements.at(component::Password) : other.m_password;
+
+ m_host = (replacements.count(component::Host))
+ ? replacements.at(component::Host) : other.m_host;
+
+ m_port = (replacements.count(component::Port))
+ ? std::stoul(replacements.at(component::Port)) : other.m_port;
+
+ m_path = (replacements.count(component::Path))
+ ? replacements.at(component::Path) : other.m_path;
+
+ m_content = (replacements.count(component::Content))
+ ? replacements.at(component::Content) : other.m_content;
+
+ m_query = (replacements.count(component::Query))
+ ? replacements.at(component::Query) : other.m_query;
+
+ m_fragment = (replacements.count(component::Fragment))
+ ? replacements.at(component::Fragment) : other.m_fragment;
+ }
+
+ // Copy constructor; just use the copy assignment operator internally.
+ uri(uri const &other)
+ {
+ *this = other;
+ };
+
+ // Copy assignment operator
+ uri &operator=(uri const &other)
+ {
+ if (this != &other)
+ {
+ m_scheme = other.m_scheme;
+ m_content = other.m_content;
+ m_username = other.m_username;
+ m_password = other.m_password;
+ m_host = other.m_host;
+ m_path = other.m_path;
+ m_query = other.m_query;
+ m_fragment = other.m_fragment;
+ m_query_dict = other.m_query_dict;
+ m_category = other.m_category;
+ m_port = other.m_port;
+ m_path_is_rooted = other.m_path_is_rooted;
+ m_separator = other.m_separator;
+ }
+ return *this;
+ }
+
+ ~uri() { };
+
+ std::string const &get_scheme() const
+ {
+ return m_scheme;
+ };
+
+ scheme_category get_scheme_category() const
+ {
+ return m_category;
+ };
+
+ std::string const &get_content() const
+ {
+ if (m_category != scheme_category::NonHierarchical)
+ {
+ throw std::domain_error("The content component is only valid for non-hierarchical URIs.");
+ }
+ return m_content;
+ };
+
+ std::string const &get_username() const
+ {
+ if (m_category != scheme_category::Hierarchical)
+ {
+ throw std::domain_error("The username component is only valid for hierarchical URIs.");
+ }
+ return m_username;
+ };
+
+ std::string const &get_password() const
+ {
+ if (m_category != scheme_category::Hierarchical)
+ {
+ throw std::domain_error("The password component is only valid for hierarchical URIs.");
+ }
+ return m_password;
+ };
+
+ std::string const &get_host() const
+ {
+ if (m_category != scheme_category::Hierarchical)
+ {
+ throw std::domain_error("The host component is only valid for hierarchical URIs.");
+ }
+ return m_host;
+ };
+
+ unsigned long get_port() const
+ {
+ if (m_category != scheme_category::Hierarchical)
+ {
+ throw std::domain_error("The port component is only valid for hierarchical URIs.");
+ }
+ return m_port;
+ };
+
+ std::string const &get_path() const
+ {
+ if (m_category != scheme_category::Hierarchical)
+ {
+ throw std::domain_error("The path component is only valid for hierarchical URIs.");
+ }
+ return m_path;
+ };
+
+ std::string const &get_query() const
+ {
+ return m_query;
+ };
+
+ std::map<std::string, std::string> const &get_query_dictionary() const
+ {
+ return m_query_dict;
+ };
+
+ std::string const &get_fragment() const
+ {
+ return m_fragment;
+ };
+
+ std::string to_string() const
+ {
+ std::string full_uri;
+ full_uri.append(m_scheme);
+ full_uri.append(":");
+
+ if (m_category == scheme_category::Hierarchical)
+ {
+ full_uri.append("//");
+ if (!(m_username.empty() || m_password.empty()))
+ {
+ full_uri.append(m_username);
+ full_uri.append(":");
+ full_uri.append(m_password);
+ full_uri.append("@");
+ }
+
+ full_uri.append(m_host);
+
+ if (m_port != 0)
+ {
+ full_uri.append(":");
+ full_uri.append(std::to_string(m_port));
+ }
+ }
+ else
+ {
+ full_uri.append(m_content);
+ }
+
+ if (m_path_is_rooted)
+ {
+ full_uri.append("/");
+ }
+ full_uri.append(m_path);
+
+ if (!m_query.empty())
+ {
+ full_uri.append("?");
+ full_uri.append(m_query);
+ }
+
+ if (!m_fragment.empty())
+ {
+ full_uri.append("#");
+ full_uri.append(m_fragment);
+ }
+
+ return full_uri;
+ };
+
+private:
+
+ void setup(std::string const &uri_text, scheme_category category)
+ {
+ size_t const uri_length = uri_text.length();
+
+ if (uri_length == 0)
+ {
+ throw std::invalid_argument("URIs cannot be of zero length.");
+ }
+
+ std::string::const_iterator cursor = parse_scheme(uri_text,
+ uri_text.begin());
+ // After calling parse_scheme, *cursor == ':'; none of the following parsers
+ // expect a separator character, so we advance the cursor upon calling them.
+ cursor = parse_content(uri_text, (cursor + 1));
+
+ if ((cursor != uri_text.end()) && (*cursor == '?'))
+ {
+ cursor = parse_query(uri_text, (cursor + 1));
+ }
+
+ if ((cursor != uri_text.end()) && (*cursor == '#'))
+ {
+ cursor = parse_fragment(uri_text, (cursor + 1));
+ }
+
+ init_query_dictionary(); // If the query string is empty, this will be empty too.
+
+ };
+
+ std::string::const_iterator parse_scheme(std::string const &uri_text,
+ std::string::const_iterator scheme_start)
+ {
+ std::string::const_iterator scheme_end = scheme_start;
+ while ((scheme_end != uri_text.end()) && (*scheme_end != ':'))
+ {
+ if (!(std::isalnum(*scheme_end) || (*scheme_end == '-')
+ || (*scheme_end == '+') || (*scheme_end == '.')))
+ {
+ throw std::invalid_argument("Invalid character found in the scheme component. Supplied URI was: \""
+ + uri_text + "\".");
+ }
+ ++scheme_end;
+ }
+
+ if (scheme_end == uri_text.end())
+ {
+ throw std::invalid_argument("End of URI found while parsing the scheme. Supplied URI was: \""
+ + uri_text + "\".");
+ }
+
+ if (scheme_start == scheme_end)
+ {
+ throw std::invalid_argument("Scheme component cannot be zero-length. Supplied URI was: \""
+ + uri_text + "\".");
+ }
+
+ m_scheme = std::string(scheme_start, scheme_end);
+ return scheme_end;
+ };
+
+ std::string::const_iterator parse_content(std::string const &uri_text,
+ std::string::const_iterator content_start)
+ {
+ std::string::const_iterator content_end = content_start;
+ while ((content_end != uri_text.end()) && (*content_end != '?') && (*content_end != '#'))
+ {
+ ++content_end;
+ }
+
+ m_content = std::string(content_start, content_end);
+
+ if ((m_category == scheme_category::Hierarchical) && (m_content.length() > 0))
+ {
+ // If it's a hierarchical URI, the content should be parsed for the hierarchical components.
+ std::string::const_iterator path_start = m_content.begin();
+ std::string::const_iterator path_end = m_content.end();
+ if (!m_content.compare(0, 2, "//"))
+ {
+ // In this case an authority component is present.
+ std::string::const_iterator authority_cursor = (m_content.begin() + 2);
+ if (m_content.find_first_of('@') != std::string::npos)
+ {
+ std::string::const_iterator userpass_divider = parse_username(uri_text,
+ m_content,
+ authority_cursor);
+ authority_cursor = parse_password(uri_text, m_content, (userpass_divider + 1));
+ // After this call, *authority_cursor == '@', so we skip over it.
+ ++authority_cursor;
+ }
+
+ authority_cursor = parse_host(uri_text, m_content, authority_cursor);
+
+ if ((authority_cursor != m_content.end()) && (*authority_cursor == ':'))
+ {
+ authority_cursor = parse_port(uri_text, m_content, (authority_cursor + 1));
+ }
+
+ if ((authority_cursor != m_content.end()) && (*authority_cursor == '/' ))
+ {
+ // Then the path is rooted, and we should note this.
+ m_path_is_rooted = true;
+ path_start = authority_cursor + 1;
+ }
+
+ // If we've reached the end and no path is present then set path_start
+ // to the end.
+ if (authority_cursor == m_content.end()) {
+ path_start = m_content.end();
+ }
+ }
+ else if (!m_content.compare(0, 1, "/"))
+ {
+ m_path_is_rooted = true;
+ ++path_start;
+ }
+
+ // We can now build the path based on what remains in the content string,
+ // since that's all that exists after the host and optional port component.
+ m_path = std::string(path_start, path_end);
+ }
+ return content_end;
+ };
+
+ std::string::const_iterator parse_username(std::string const &uri_text,
+ std::string const &content,
+ std::string::const_iterator username_start)
+ {
+ std::string::const_iterator username_end = username_start;
+ // Since this is only reachable when '@' was in the content string, we can
+ // ignore the end-of-string case.
+ while (*username_end != ':')
+ {
+ if (*username_end == '@')
+ {
+ throw std::invalid_argument("Username must be followed by a password. Supplied URI was: \""
+ + uri_text + "\".");
+ }
+ ++username_end;
+ }
+ m_username = std::string(username_start, username_end);
+ return username_end;
+ };
+
+ std::string::const_iterator parse_password(std::string const &uri_text,
+ std::string const &content,
+ std::string::const_iterator password_start)
+ {
+ std::string::const_iterator password_end = password_start;
+ while (*password_end != '@')
+ {
+ ++password_end;
+ }
+
+ m_password = std::string(password_start, password_end);
+ return password_end;
+ };
+
+ std::string::const_iterator parse_host(std::string const &uri_text,
+ std::string const &content,
+ std::string::const_iterator host_start)
+ {
+ std::string::const_iterator host_end = host_start;
+ // So, the host can contain a few things. It can be a domain, it can be an
+ // IPv4 address, it can be an IPv6 address, or an IPvFuture literal. In the
+ // case of those last two, it's of the form [...] where what's between the
+ // brackets is a matter of which IPv?? version it is.
+ while (host_end != content.end())
+ {
+ if (*host_end == '[')
+ {
+ // We're parsing an IPv6 or IPvFuture address, so we should handle that
+ // instead of the normal procedure.
+ while ((host_end != content.end()) && (*host_end != ']'))
+ {
+ ++host_end;
+ }
+
+ if (host_end == content.end())
+ {
+ throw std::invalid_argument("End of content component encountered "
+ "while parsing the host component. "
+ "Supplied URI was: \""
+ + uri_text + "\".");
+ }
+
+ ++host_end;
+ break;
+ // We can stop looping, we found the end of the IP literal, which is the
+ // whole of the host component when one's in use.
+ }
+ else if ((*host_end == ':') || (*host_end == '/'))
+ {
+ break;
+ }
+ else
+ {
+ ++host_end;
+ }
+ }
+
+ m_host = std::string(host_start, host_end);
+ return host_end;
+ };
+
+ std::string::const_iterator parse_port(std::string const &uri_text,
+ std::string const &content,
+ std::string::const_iterator port_start)
+ {
+ std::string::const_iterator port_end = port_start;
+ while ((port_end != content.end()) && (*port_end != '/'))
+ {
+ if (!std::isdigit(*port_end))
+ {
+ throw std::invalid_argument("Invalid character while parsing the port. "
+ "Supplied URI was: \"" + uri_text + "\".");
+ }
+
+ ++port_end;
+ }
+
+ m_port = std::stoul(std::string(port_start, port_end));
+ return port_end;
+ };
+
+ std::string::const_iterator parse_query(std::string const &uri_text,
+ std::string::const_iterator query_start)
+ {
+ std::string::const_iterator query_end = query_start;
+ while ((query_end != uri_text.end()) && (*query_end != '#'))
+ {
+ // Queries can contain almost any character except hash, which is reserved
+ // for the start of the fragment.
+ ++query_end;
+ }
+ m_query = std::string(query_start, query_end);
+ return query_end;
+ };
+
+ std::string::const_iterator parse_fragment(std::string const &uri_text,
+ std::string::const_iterator fragment_start)
+ {
+ m_fragment = std::string(fragment_start, uri_text.end());
+ return uri_text.end();
+ };
+
+ void init_query_dictionary()
+ {
+ if (!m_query.empty())
+ {
+ // Loop over the query string looking for '&'s, then check each one for
+ // an '=' to find keys and values; if there's not an '=' then the key
+ // will have an empty value in the map.
+ char separator = (m_separator == query_argument_separator::ampersand) ? '&' : ';';
+ size_t carat = 0;
+ size_t stanza_end = m_query.find_first_of(separator);
+ do
+ {
+ std::string stanza = m_query.substr(carat, ((stanza_end != std::string::npos) ? (stanza_end - carat) : std::string::npos));
+ size_t key_value_divider = stanza.find_first_of('=');
+ std::string key = stanza.substr(0, key_value_divider);
+ std::string value;
+ if (key_value_divider != std::string::npos)
+ {
+ value = stanza.substr((key_value_divider + 1));
+ }
+
+ if (m_query_dict.count(key) != 0)
+ {
+ throw std::invalid_argument("Bad key in the query string!");
+ }
+
+ m_query_dict.emplace(key, value);
+ carat = ((stanza_end != std::string::npos) ? (stanza_end + 1)
+ : std::string::npos);
+ stanza_end = m_query.find_first_of(separator, carat);
+ }
+ while ((stanza_end != std::string::npos)
+ || (carat != std::string::npos));
+ }
+ }
+
+ std::string m_scheme;
+ std::string m_content;
+ std::string m_username;
+ std::string m_password;
+ std::string m_host;
+ std::string m_path;
+ std::string m_query;
+ std::string m_fragment;
+
+ std::map<std::string, std::string> m_query_dict;
+
+ scheme_category m_category;
+ unsigned long m_port;
+ bool m_path_is_rooted;
+ query_argument_separator m_separator;
+};