blob: e4eca2ac8851432c245424f430032125a3e88977 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
/*
* File: net/url.hpp
* Purpose: URL container in modern C++
* Author: Amlal El Mahrouss (amlal@nekernel.org)
* Copyright 2025, Amlal El Mahrouss, licensed under the MIT license.
*/
#pragma once
#include <string>
#include <sstream>
/// @author Amlal El Mahrouss (amlal@nekernel.org)
/// @brief Parse URLs (in a non-standard way).
namespace ocl::net
{
template <typename char_type>
class basic_url;
enum class url_protocol
{
invalid = 0,
http,
https,
mailto,
bad = 0xff,
};
/// @brief Basic URL parser container.
template <typename char_type>
class basic_url final
{
url_protocol m_protocol_{url_protocol::invalid};
std::basic_stringstream<char_type> m_ss_{};
std::basic_string<char_type> m_port_{""};
public:
explicit basic_url(const std::basic_string<char_type>& protocol)
{
if (protocol.starts_with("https://"))
{
m_protocol_ = url_protocol::https;
this->operator/=(protocol.substr(strlen("https://")));
}
else if (protocol.starts_with("http://"))
{
m_protocol_ = url_protocol::http;
this->operator/=(protocol.substr(strlen("http://")));
}
else if (protocol.starts_with("mailto:"))
{
m_protocol_ = url_protocol::mailto;
this->operator/=(protocol.substr(strlen("mailto:")));
}
}
~basic_url() = default;
basic_url& operator=(const basic_url&) = default;
basic_url(const basic_url&) = default;
private:
basic_url& operator/=(const std::basic_string<char_type>& in)
{
if (in.empty())
return *this;
if (in.starts_with(":"))
{
m_port_ = in.substr(1);
return *this;
}
m_ss_ += in;
return *this;
}
basic_url& operator/=(const char_type& in)
{
m_ss_ += in;
return *this;
}
explicit operator bool()
{
return this->is_valid();
}
public:
auto protocol() const noexcept
{
return this->m_protocol_;
}
auto port() const noexcept
{
return this->m_port_;
}
auto is_valid() const noexcept
{
return m_ss_.size() > 0 && this->m_protocol_ != url_protocol::bad || this->m_protocol_ != url_protocol::invalid;
}
};
using url = basic_url<char>;
} // namespace ocl::net
|