2020-02-26 11:57:18 +00:00
|
|
|
#ifndef ARBUTILS_CONSTSTRING_HPP
|
|
|
|
#define ARBUTILS_CONSTSTRING_HPP
|
|
|
|
|
|
|
|
#include <cstddef>
|
|
|
|
#include <cstdint>
|
|
|
|
#include <cstring>
|
|
|
|
#include <string>
|
2020-02-27 12:42:26 +00:00
|
|
|
|
2020-02-26 11:57:18 +00:00
|
|
|
namespace Arbutils {
|
|
|
|
class ConstString {
|
|
|
|
private:
|
|
|
|
const char* _str;
|
|
|
|
size_t _length;
|
|
|
|
uint32_t _hash;
|
|
|
|
|
|
|
|
inline static uint32_t constexpr Hash(char const* input) {
|
|
|
|
return (*input) ? static_cast<uint32_t>((*input)) + 33 * Hash(input + 1) : 5381;
|
|
|
|
}
|
|
|
|
inline static int constexpr Length(const char* str) { return *str ? 1 + Length(str + 1) : 0; }
|
|
|
|
|
|
|
|
public:
|
2020-02-27 12:42:26 +00:00
|
|
|
constexpr ConstString() : _str(""), _length(0), _hash(Hash("")){};
|
2020-02-26 11:57:18 +00:00
|
|
|
constexpr explicit ConstString(const char* str) : _str(str), _length(Length(str)), _hash(Hash(str)){};
|
2020-02-27 12:42:26 +00:00
|
|
|
constexpr explicit ConstString(const char* str, size_t size) : _str(str), _length(size), _hash(Hash(str)){};
|
2020-02-26 11:57:18 +00:00
|
|
|
|
2020-02-26 12:01:21 +00:00
|
|
|
[[nodiscard]] inline constexpr const char* c_str() const noexcept { return _str; }
|
|
|
|
[[nodiscard]] inline std::string std_str() const { return std::string(_str, _length); }
|
2020-02-26 11:57:18 +00:00
|
|
|
|
2020-02-26 12:01:21 +00:00
|
|
|
[[nodiscard]] inline constexpr size_t Length() const noexcept { return _length; }
|
2020-02-26 11:57:18 +00:00
|
|
|
|
2020-02-26 12:01:21 +00:00
|
|
|
[[nodiscard]] inline constexpr uint32_t GetHash() const noexcept { return _hash; }
|
2020-02-27 12:42:26 +00:00
|
|
|
|
|
|
|
constexpr std::size_t operator()(ConstString const& s) const noexcept { return s.GetHash(); }
|
|
|
|
inline constexpr operator uint32_t() const{ return _hash; }
|
|
|
|
|
|
|
|
inline constexpr bool operator==(const ConstString& rhs) const{
|
|
|
|
return _hash == rhs._hash;
|
|
|
|
}
|
|
|
|
inline constexpr bool operator!=(const ConstString& rhs) const{
|
|
|
|
return _hash != rhs._hash;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
inline constexpr Arbutils::ConstString operator"" _const(const char* c, unsigned long l) {
|
|
|
|
return Arbutils::ConstString(c, l);
|
|
|
|
}
|
|
|
|
inline constexpr Arbutils::ConstString operator"" _c(const char* c, unsigned long l) {
|
|
|
|
return Arbutils::ConstString(c, l);
|
|
|
|
}
|
|
|
|
|
|
|
|
namespace std {
|
|
|
|
template <> struct hash<Arbutils::ConstString> {
|
|
|
|
constexpr std::size_t operator()(Arbutils::ConstString const& s) const noexcept { return s.GetHash(); }
|
2020-02-26 11:57:18 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
#endif // ARBUTILS_CONSTSTRING_HPP
|