larra/library/src/jid.cpp

81 lines
2.5 KiB
C++
Raw Normal View History

2024-08-29 16:42:58 +00:00
#include <format>
#include <larra/jid.hpp>
namespace larra::xmpp {
auto ParseBareJid(std::string_view jid, std::size_t at) -> BareJid {
return {.username = static_cast<std::string>(jid.substr(0, at)), .server = static_cast<std::string>(jid.substr(at + 1))};
2024-08-29 16:42:58 +00:00
}
auto ParseBareResourceJid(std::string_view jid, std::size_t slash) -> BareResourceJid {
return {.server = static_cast<std::string>(jid.substr(0, slash)), .resource = static_cast<std::string>(jid.substr(slash + 1))};
2024-08-29 16:42:58 +00:00
}
auto ParseFullJid(std::string_view jid, std::size_t at, std::size_t slash) -> FullJid {
return {.username = static_cast<std::string>(jid.substr(0, at)),
.server = static_cast<std::string>(jid.substr(at + 1, slash - at - 1)),
.resource = static_cast<std::string>(jid.substr(slash + 1))};
2024-08-29 16:42:58 +00:00
}
auto BareJid::Parse(std::string_view jid) -> BareJid {
const auto at = jid.find('@');
if(at == std::string_view::npos) {
throw std::invalid_argument("Invalid string for jid");
}
return ParseBareJid(jid, at);
}
auto BareResourceJid::Parse(std::string_view jid) -> BareResourceJid {
const auto slash = jid.find('/');
if(slash == std::string_view::npos) {
throw std::invalid_argument("Invalid string for jid");
}
return ParseBareResourceJid(jid, slash);
}
auto FullJid::Parse(std::string_view jid) -> FullJid {
const auto at = jid.find('@');
const auto slash = jid.find('/', at);
if(at == std::string_view::npos || slash == std::string_view::npos) {
throw std::invalid_argument("Invalid string for jid");
}
return ParseFullJid(jid, at, slash);
}
auto Jid::Parse(std::string_view jid) -> Jid {
const auto at = jid.find('@');
const auto slash = jid.find('/', at == std::string_view::npos ? 0 : at);
if(at == std::string_view::npos) {
return ParseBareResourceJid(jid, slash);
}
if(slash == std::string_view::npos) {
return ParseBareJid(jid, at);
}
return ParseFullJid(jid, at, slash);
}
auto ToString(const BareJid& jid) -> std::string {
return std::format("{}@{}", jid.username, jid.server);
}
auto ToString(const BareResourceJid& jid) -> std::string {
return std::format("{}/{}", jid.server, jid.resource);
}
auto ToString(const FullJid& jid) -> std::string {
return std::format("{}@{}/{}", jid.username, jid.server, jid.resource);
}
auto ToString(const Jid& jid) -> std::string {
return std::visit<std::string>(
[](const auto& jid) -> std::string {
return ToString(jid);
},
jid);
}
} // namespace larra::xmpp