tb_hash.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // ================================================================================
  2. // == This file is a part of Turbo Badger. (C) 2011-2014, Emil Segerås ==
  3. // == See tb_core.h for more information. ==
  4. // ================================================================================
  5. #ifndef TB_HASH_H
  6. #define TB_HASH_H
  7. #include "tb_types.h"
  8. namespace tb {
  9. // On C++ compilers that support it, use const expr for hash so that
  10. // TBID comparisions turn into simple uint32 comparisions compiletime.
  11. // Disabled for TB_RUNTIME_DEBUG_INFO builds, so TBID string debugging
  12. // is available.
  13. //
  14. // Note: GCC may need -std=c++0x or -std=c++11 to enable this feature.
  15. #ifndef TB_RUNTIME_DEBUG_INFO
  16. #if defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L
  17. #define TB_SUPPORT_CONSTEXPR
  18. #endif
  19. #endif
  20. #ifdef TB_SUPPORT_CONSTEXPR
  21. // FNV constants
  22. static constexpr uint32 basis = 2166136261U;
  23. static constexpr uint32 prime = 16777619U;
  24. // compile-time hash helper function
  25. constexpr uint32 TBGetHash_one(char c, const char* remain, uint32 value)
  26. {
  27. return c == 0 ? value : TBGetHash_one(remain[0], remain + 1, (value ^ c) * prime);
  28. }
  29. // compile-time hash
  30. constexpr uint32 TBGetHash(const char* str)
  31. {
  32. return (str && *str) ? TBGetHash_one(str[0], str + 1, basis) : 0;
  33. }
  34. #define TBIDC(str) TBGetHash(str)
  35. #else // TB_SUPPORT_CONSTEXPR
  36. #define TBIDC(str) TBID(str)
  37. /** Get hash value from string */
  38. uint32 TBGetHash(const char *str);
  39. #endif // !TB_SUPPORT_CONSTEXPR
  40. }; // namespace tb
  41. #endif // TB_HASH_H