string_id.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright (c) 2012-2018 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/dbartolini/crown/blob/master/LICENSE
  4. */
  5. #include "core/error/error.h"
  6. #include "core/murmur.h"
  7. #include "core/strings/string.h"
  8. #include "core/strings/string_id.h"
  9. #include <inttypes.h> // PRIx64
  10. namespace crown
  11. {
  12. StringId32::StringId32(const char* str)
  13. {
  14. hash(str, strlen32(str));
  15. }
  16. StringId32::StringId32(const char* str, u32 len)
  17. {
  18. hash(str, len);
  19. }
  20. void StringId32::hash(const char* str, u32 len)
  21. {
  22. CE_ENSURE(NULL != str);
  23. _id = murmur32(str, len, 0);
  24. }
  25. void StringId32::parse(const char* str)
  26. {
  27. CE_ENSURE(NULL != str);
  28. int num = sscanf(str, "%8x", &_id);
  29. CE_ENSURE(num == 1);
  30. CE_UNUSED(num);
  31. }
  32. void StringId32::to_string(char* buf, u32 len) const
  33. {
  34. snprintf(buf, len, "%.8x", _id);
  35. }
  36. StringId64::StringId64(const char* str)
  37. {
  38. hash(str, strlen32(str));
  39. }
  40. StringId64::StringId64(const char* str, u32 len)
  41. {
  42. hash(str, len);
  43. }
  44. void StringId64::hash(const char* str, u32 len)
  45. {
  46. CE_ENSURE(NULL != str);
  47. _id = murmur64(str, len, 0);
  48. }
  49. void StringId64::parse(const char* str)
  50. {
  51. u32 id[2];
  52. CE_ENSURE(NULL != str);
  53. int num = sscanf(str, "%8x%8x", &id[0], &id[1]);
  54. _id = 0;
  55. _id |= u64(id[0]) << 32;
  56. _id |= u64(id[1]) << 0;
  57. CE_ENSURE(num == 2);
  58. CE_UNUSED(num);
  59. }
  60. void StringId64::to_string(char* buf, u32 len) const
  61. {
  62. snprintf(buf, len, "%.16" PRIx64, _id);
  63. }
  64. } // namespace crown