HashedString.cppm 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. module;
  2. #include <cstdio>
  3. #include <cstring>
  4. export module Core.HashedString;
  5. export import Core.Types;
  6. export namespace Core {
  7. struct StringHash {
  8. size_t length = 0;
  9. size_t hash = 0;
  10. };
  11. constexpr StringHash hashString(const char* s) {
  12. StringHash h;
  13. while(*s != '\0') {
  14. h.length++;
  15. h.hash = 2'120'251'889lu * h.hash + static_cast<size_t>(*(s++));
  16. }
  17. return h;
  18. }
  19. template<size_t N>
  20. class HashedString {
  21. StringHash hash;
  22. char data[N];
  23. public:
  24. HashedString() : hash(), data{} {
  25. }
  26. HashedString(const char* s) : hash(hashString(s)) {
  27. snprintf(data, N, "%s", s);
  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. size_t getLength() const {
  38. return hash.length;
  39. }
  40. constexpr size_t getCapacity() const {
  41. return N - 1;
  42. }
  43. size_t hashCode() const {
  44. return hash.hash;
  45. }
  46. operator const char*() const {
  47. return data;
  48. }
  49. };
  50. }