HashedString.hpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #ifndef CORE_HASHED_STRING_HPP
  2. #define CORE_HASHED_STRING_HPP
  3. #include <string.h>
  4. #include "core/utils/Types.hpp"
  5. namespace Core {
  6. struct StringHash {
  7. size_t length = 0;
  8. size_t hash = 0;
  9. };
  10. constexpr StringHash hashString(const char* s) {
  11. StringHash h;
  12. while(*s != '\0') {
  13. h.length++;
  14. h.hash = 2120251889lu * h.hash + static_cast<size_t>(*(s++));
  15. }
  16. return h;
  17. }
  18. template<size_t N>
  19. class HashedString {
  20. StringHash hash;
  21. char data[N];
  22. public:
  23. HashedString() : hash() {
  24. }
  25. HashedString(const char* s) : hash(hashString(s)) {
  26. strncpy(data, s, N);
  27. }
  28. bool operator==(const HashedString& other) const {
  29. return hash.length == other.hash.length &&
  30. hash.hash == other.hash.hash &&
  31. strcmp(data, other.data) == 0;
  32. }
  33. bool operator!=(const HashedString& other) const {
  34. return !(*this == other);
  35. }
  36. size_t getLength() const {
  37. return hash.length;
  38. }
  39. constexpr size_t getCapacity() const {
  40. return N - 1;
  41. }
  42. size_t hashCode() const {
  43. return hash.hash;
  44. }
  45. operator const char*() const {
  46. return data;
  47. }
  48. };
  49. }
  50. #endif