HashedString.cppm 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. module;
  2. #include <cstdio>
  3. export module Core.HashedString;
  4. export import Core.Types;
  5. import Core.Std;
  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. }