Arbutils/src/ConstString.hpp

34 lines
1.1 KiB
C++
Raw Normal View History

2020-02-26 11:57:18 +00:00
#ifndef ARBUTILS_CONSTSTRING_HPP
#define ARBUTILS_CONSTSTRING_HPP
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <string>
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:
constexpr explicit ConstString(const char* str) : _str(str), _length(Length(str)), _hash(Hash(str)){};
[[nodiscard]] constexpr const char* c_str() const noexcept { return _str; }
[[nodiscard]] std::string std_str() const { return std::string(_str, _length); }
[[nodiscard]] constexpr size_t Length() const noexcept { return _length; }
[[nodiscard]] constexpr uint32_t GetHash() const noexcept { return _hash; }
};
constexpr ConstString operator"" _const(const char* c) { return ConstString(c); }
}
#endif // ARBUTILS_CONSTSTRING_HPP