HashedString.hpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. i32 length = 0;
  8. u32 hash = 0;
  9. };
  10. constexpr StringHash hashString(const char* s) {
  11. StringHash h;
  12. while(*s != '\0') {
  13. h.length++;
  14. h.hash = 2120251889u * h.hash + static_cast<u32>(*(s++));
  15. }
  16. return h;
  17. }
  18. template<i32 N>
  19. class HashedString {
  20. static_assert(N > 0, "length of hashed string must be positive");
  21. StringHash hash;
  22. char data[static_cast<u32>(N)];
  23. public:
  24. HashedString() : hash() {
  25. }
  26. HashedString(const char* s) : hash(hashString(s)) {
  27. strncpy(data, s, N);
  28. }
  29. bool operator==(const HashedString& other) const {
  30. return hash.length == other.hash.length &&
  31. hash.hash == other.hash.hash &&
  32. strcmp(data, other.data) == 0;
  33. }
  34. bool operator!=(const HashedString& other) const {
  35. return !(*this == other);
  36. }
  37. i32 getLength() const {
  38. return hash.length;
  39. }
  40. constexpr i32 getCapacity() const {
  41. return N - 1;
  42. }
  43. u32 hashCode() const {
  44. return hash.hash;
  45. }
  46. operator const char*() const {
  47. return data;
  48. }
  49. };
  50. }
  51. #endif