1
0
Fork 0
mirror of https://gitlab.com/niansa/asbots.git synced 2025-03-06 20:48:25 +01:00
asbots/uid.hpp
2021-06-21 15:54:49 +02:00

118 lines
2.9 KiB
C++

/*
* asbots
* Copyright (C) 2021 niansa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef _UID_HPP
#define _UID_HPP
#include <string>
#include <string_view>
#include <array>
#include <variant>
template<int len>
class UID {
public:
std::array<char, len> array;
constexpr UID() : array({'\0'}) {}
constexpr UID(std::string_view initializer) {
for (typeof(len) it = 0; it != len; it++) {
array[it] = *(initializer.begin() + it);
}
//array[len] = '\0';
}
constexpr UID(const char *initializer) {
*this = UID(std::string_view{initializer, len});
}
constexpr bool operator ==(const UID& other) {
return str() == other.str();
}
constexpr bool has_value() const {
return array[0] != '\0';
}
constexpr std::string_view str() const {
if (has_value()) {
return {array.begin(), static_cast<std::string_view::size_type>(len)};
} else {
return "NUL_V";
}
}
};
constexpr int SUID_len = 3;
constexpr int UUID_len = 9;
using SUID = UID<SUID_len>;
using UUID = UID<UUID_len>;
struct AnyUID {
std::variant<SUID, UUID, std::string, std::nullptr_t> id;
enum Type {
USER,
SERVER,
OTHER,
NUL
} type = NUL;
std::string_view str() const {
if (type == SERVER) {
return std::get<SUID>(id).str();
} else if (type == USER) {
return std::get<UUID>(id).str();
} else if (type == OTHER) {
return std::get<std::string>(id);
} else {
return "NUL_T";
}
}
bool operator ==(const AnyUID& other) {
return str() == other.str();
}
void assign(const SUID& val) {
type = SERVER;
id = val;
}
void assign(const UUID& val) {
type = USER;
id = val;
}
void assign(std::string_view val) {
type = OTHER;
id = std::string(val);
}
void assign(const char *val) {
type = OTHER;
id = std::string(val);
}
void assign(std::nullptr_t) {
type = NUL;
id = nullptr;
}
AnyUID() {}
template<typename T>
AnyUID(const T& val) {
assign(val);
}
explicit AnyUID(const AnyUID& o) : id(o.id), type(o.type) {}
};
#endif