hash_unittest.cc 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2014 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "butil/hash.h"
  5. #include <string>
  6. #include <vector>
  7. #include <gtest/gtest.h>
  8. namespace butil {
  9. TEST(HashTest, String) {
  10. std::string str;
  11. // Empty string (should hash to 0).
  12. str = "";
  13. EXPECT_EQ(0u, Hash(str));
  14. // Simple test.
  15. str = "hello world";
  16. EXPECT_EQ(2794219650u, Hash(str));
  17. // Change one bit.
  18. str = "helmo world";
  19. EXPECT_EQ(1006697176u, Hash(str));
  20. // Insert a null byte.
  21. str = "hello world";
  22. str[5] = '\0';
  23. EXPECT_EQ(2319902537u, Hash(str));
  24. // Test that the bytes after the null contribute to the hash.
  25. str = "hello worle";
  26. str[5] = '\0';
  27. EXPECT_EQ(553904462u, Hash(str));
  28. // Extremely long string.
  29. // Also tests strings with high bit set, and null byte.
  30. std::vector<char> long_string_buffer;
  31. for (int i = 0; i < 4096; ++i)
  32. long_string_buffer.push_back((i % 256) - 128);
  33. str.assign(&long_string_buffer.front(), long_string_buffer.size());
  34. EXPECT_EQ(2797962408u, Hash(str));
  35. // All possible lengths (mod 4). Tests separate code paths. Also test with
  36. // final byte high bit set (regression test for http://crbug.com/90659).
  37. // Note that the 1 and 3 cases have a weird bug where the final byte is
  38. // treated as a signed char. It was decided on the above bug discussion to
  39. // enshrine that behaviour as "correct" to avoid invalidating existing hashes.
  40. // Length mod 4 == 0.
  41. str = "hello w\xab";
  42. EXPECT_EQ(615571198u, Hash(str));
  43. // Length mod 4 == 1.
  44. str = "hello wo\xab";
  45. EXPECT_EQ(623474296u, Hash(str));
  46. // Length mod 4 == 2.
  47. str = "hello wor\xab";
  48. EXPECT_EQ(4278562408u, Hash(str));
  49. // Length mod 4 == 3.
  50. str = "hello worl\xab";
  51. EXPECT_EQ(3224633008u, Hash(str));
  52. }
  53. TEST(HashTest, CString) {
  54. const char* str;
  55. // Empty string (should hash to 0).
  56. str = "";
  57. EXPECT_EQ(0u, Hash(str, strlen(str)));
  58. // Simple test.
  59. str = "hello world";
  60. EXPECT_EQ(2794219650u, Hash(str, strlen(str)));
  61. // Ensure that it stops reading after the given length, and does not expect a
  62. // null byte.
  63. str = "hello world; don't read this part";
  64. EXPECT_EQ(2794219650u, Hash(str, strlen("hello world")));
  65. }
  66. } // namespace butil