Files
core_misc/tjp/core/url/URL.cpp
Timothy Prepscius fa54be052a flatten 20260225
2026-02-25 12:39:24 -05:00

156 lines
2.2 KiB
C++
Executable File

// TJP COPYRIGHT HEADER
#include "URL.h"
#include <tjp/core/string/str_find.h>
#include <tjp/core/algorithm/is_in.hpp>
#include <tjp/core/iterators/range.hpp>
#include <tjp/core/assert/debug_assert.h>
#include <tjp/core/algorithm/unused.hpp>
namespace tjp::core::url {
const char S = '/';
const char D = '#';
const char P = ':';
URL make(const Domain &domain)
{
debug_assert(domain.find(D)==-1);
debug_assert(domain.find(S)==-1);
return domain + D;
}
IP getIP(const URL &url)
{
auto p = url.find(P);
if (p == -1)
return {};
return url.substr(0,p);
}
Address getAddress(const URL &url)
{
auto d = url.find(D);
if (d == -1)
return {};
return url.substr(0,d);
}
Domain getDomain(const URL &url)
{
auto d = url.find(D);
return url.substr(0,d+1);
}
Path getPath(const URL &url)
{
return url.substr(url.find(D) + 1);
}
URL push_back(const URL &lhs, const URL &rhs)
{
debug_assert(rhs.find(D)==-1);
if (rhs.empty())
return lhs;
auto domain = getDomain(lhs);
auto path0 = getPath(lhs);
auto path1 = getPath(rhs);
auto s0 = path0.empty() ? "" : (path1.empty() ? "" : "/");
return domain + path0 + s0 + path1;
}
URL pop_back_(const URL &url)
{
int i;
for (i=(int)url.size()-1; i>0; --i)
if (is_in(url[i], D, S))
break;
if (i < 0)
return {};
if (url[i] == D)
return url.substr(0,i+1);
return url.substr(0,i);
}
URL pop_front_(const URL &url)
{
int i;
for (i=0; i<url.size(); ++i)
if (is_in(url[i], D, S))
break;
if (i >= url.size())
return {};
return url.substr(i+1);
}
URL pop_back(const URL &url_, size_t num)
{
auto url = url_;
for (auto i : range(num))
{
unused(i);
url = pop_back_(url);
}
return url;
}
URL pop_front(const URL &url_, size_t num)
{
auto url = url_;
for (auto i : range(num))
{
unused(i);
url = pop_front_(url);
}
return url;
}
URL back(const URL &url)
{
int i;
for (i=(int)url.size()-1; i>=0; --i)
{
if (is_in(url[i], D, S))
break;
}
return url.substr(i+1);
}
URL front(const URL &url)
{
auto path = getPath(url);
int i;
for (i=0; i<path.size(); ++i)
if (is_in(path[i], D, S))
break;
return url.substr(0, i);
}
bool hasPath(const URL &url)
{
return !getPath(url).empty();
}
} // namespace