HashedString.cppm 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. export module Core.HashedString;
  2. export import Core.Types;
  3. import Core.Std;
  4. import Core.ToString;
  5. export namespace Core {
  6. struct StringHash {
  7. size_t length = 0;
  8. size_t hash = 0;
  9. };
  10. constexpr StringHash hashString(const char* s) noexcept {
  11. StringHash h;
  12. while(*s != '\0') {
  13. h.length++;
  14. h.hash = 2'120'251'889lu * 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() noexcept : hash(), data{} {
  24. }
  25. HashedString(const char* s) noexcept : hash(hashString(s)) {
  26. Core::StringBase(data, N).add(s);
  27. }
  28. bool operator==(const HashedString& other) const noexcept {
  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 noexcept {
  34. return !(*this == other);
  35. }
  36. size_t getLength() const noexcept {
  37. return hash.length;
  38. }
  39. constexpr size_t getCapacity() const noexcept {
  40. return N - 1;
  41. }
  42. size_t hashCode() const noexcept {
  43. return hash.hash;
  44. }
  45. operator const char*() const noexcept {
  46. return data;
  47. }
  48. };
  49. }