1 /*
2 *
3 * Copyright 2015 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #include "src/core/lib/gpr/murmur_hash.h"
20 #include <grpc/support/log.h>
21 #include <grpc/support/string_util.h>
22 #include "test/core/util/test_config.h"
23
24 #include <string.h>
25
26 typedef uint32_t (*hash_func)(const void* key, size_t len, uint32_t seed);
27
28 /* From smhasher:
29 This should hopefully be a thorough and uambiguous test of whether a hash
30 is correctly implemented on a given platform */
31
verification_test(hash_func hash,uint32_t expected)32 static void verification_test(hash_func hash, uint32_t expected) {
33 uint8_t key[256];
34 uint32_t hashes[256];
35 uint32_t final = 0;
36 size_t i;
37
38 memset(key, 0, sizeof(key));
39 memset(hashes, 0, sizeof(hashes));
40
41 /* Hash keys of the form {0}, {0,1}, {0,1,2}... up to N=255,using 256-N as
42 the seed */
43
44 for (i = 0; i < 256; i++) {
45 key[i] = static_cast<uint8_t>(i);
46 hashes[i] = hash(key, i, static_cast<uint32_t>(256u - i));
47 }
48
49 /* Then hash the result array */
50
51 final = hash(hashes, sizeof(hashes), 0);
52
53 /* The first four bytes of that hash, interpreted as a little-endian integer,
54 is our
55 verification value */
56
57 if (expected != final) {
58 gpr_log(GPR_INFO, "Verification value 0x%08X : Failed! (Expected 0x%08x)",
59 final, expected);
60 abort();
61 } else {
62 gpr_log(GPR_INFO, "Verification value 0x%08X : Passed!", final);
63 }
64 }
65
main(int argc,char ** argv)66 int main(int argc, char** argv) {
67 grpc_test_init(argc, argv);
68 /* basic tests to verify that things don't crash */
69 gpr_murmur_hash3("", 0, 0);
70 gpr_murmur_hash3("xyz", 3, 0);
71 verification_test(gpr_murmur_hash3, 0xB0F57EE3);
72 return 0;
73 }
74