StringHash.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "MathDefs.h"
  24. #include "StringHash.h"
  25. #include <cstdio>
  26. #include "DebugNew.h"
  27. namespace Urho3D
  28. {
  29. const StringHash StringHash::ZERO;
  30. const ShortStringHash ShortStringHash::ZERO;
  31. StringHash::StringHash(const char* str) :
  32. value_(Calculate(str))
  33. {
  34. }
  35. StringHash::StringHash(const String& str) :
  36. value_(Calculate(str.CString()))
  37. {
  38. }
  39. unsigned StringHash::Calculate(const char* str)
  40. {
  41. unsigned hash = 0;
  42. if (!str)
  43. return hash;
  44. while (*str)
  45. {
  46. // Perform the actual hashing as case-insensitive
  47. char c = *str;
  48. hash = SDBMHash(hash, tolower(c));
  49. ++str;
  50. }
  51. return hash;
  52. }
  53. String StringHash::ToString() const
  54. {
  55. char tempBuffer[CONVERSION_BUFFER_LENGTH];
  56. sprintf(tempBuffer, "%08X", value_);
  57. return String(tempBuffer);
  58. }
  59. ShortStringHash::ShortStringHash(const char* str) :
  60. value_(Calculate(str))
  61. {
  62. }
  63. ShortStringHash::ShortStringHash(const String& str) :
  64. value_(Calculate(str.CString()))
  65. {
  66. }
  67. unsigned short ShortStringHash::Calculate(const char* str)
  68. {
  69. return StringHash::Calculate(str);
  70. }
  71. String ShortStringHash::ToString() const
  72. {
  73. char tempBuffer[CONVERSION_BUFFER_LENGTH];
  74. sprintf(tempBuffer, "%04X", value_);
  75. return String(tempBuffer);
  76. }
  77. }