Support for using ConstString in unordered_maps and switch case statements.
continuous-integration/drone/push Build is failing Details

This commit is contained in:
Deukhoofd 2020-02-27 13:42:26 +01:00
parent 7505e9ca23
commit f8ecebef8c
Signed by: Deukhoofd
GPG Key ID: ADF2E9256009EDCE
2 changed files with 52 additions and 1 deletions

View File

@ -5,6 +5,7 @@
#include <cstdint>
#include <cstring>
#include <string>
namespace Arbutils {
class ConstString {
private:
@ -18,7 +19,9 @@ namespace Arbutils {
inline static int constexpr Length(const char* str) { return *str ? 1 + Length(str + 1) : 0; }
public:
constexpr ConstString() : _str(""), _length(0), _hash(Hash("")){};
constexpr explicit ConstString(const char* str) : _str(str), _length(Length(str)), _hash(Hash(str)){};
constexpr explicit ConstString(const char* str, size_t size) : _str(str), _length(size), _hash(Hash(str)){};
[[nodiscard]] inline constexpr const char* c_str() const noexcept { return _str; }
[[nodiscard]] inline std::string std_str() const { return std::string(_str, _length); }
@ -26,8 +29,30 @@ namespace Arbutils {
[[nodiscard]] inline constexpr size_t Length() const noexcept { return _length; }
[[nodiscard]] inline constexpr uint32_t GetHash() const noexcept { return _hash; }
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(); }
};
inline constexpr ConstString operator"" _const(const char* c) { return ConstString(c); }
}
#endif // ARBUTILS_CONSTSTRING_HPP

View File

@ -0,0 +1,26 @@
#ifdef TESTS_BUILD
#include <cstring>
#include <unordered_map>
#include "../extern/catch.hpp"
#include "../src/ConstString.hpp"
TEST_CASE("Use const string in unordered_map", "[Utilities]") {
std::unordered_map<Arbutils::ConstString, int32_t> map;
map.insert({"foo"_c, 1});
map.insert({"bar"_c, 5});
CHECK(map["bar"_c] == 5);
CHECK(map["foo"_c] == 1);
}
TEST_CASE("Use const string in switch case", "[Utilities]") {
auto val = Arbutils::ConstString("foobar");
switch (val){
case "foo"_c: FAIL(); break;
case "bar"_c: FAIL(); break;
case "foobar"_c: SUCCEED(); break;
default: FAIL(); break;
}
}
#endif