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