murmur_hash_test.cc 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. #include "src/core/lib/gpr/murmur_hash.h"
  19. #include <string.h>
  20. #include <grpc/support/log.h>
  21. #include <grpc/support/string_util.h>
  22. #include "test/core/util/test_config.h"
  23. typedef uint32_t (*hash_func)(const void* key, size_t len, uint32_t seed);
  24. /* From smhasher:
  25. This should hopefully be a thorough and uambiguous test of whether a hash
  26. is correctly implemented on a given platform */
  27. static void verification_test(hash_func hash, uint32_t expected) {
  28. uint8_t key[256];
  29. uint32_t hashes[256];
  30. uint32_t final = 0;
  31. size_t i;
  32. memset(key, 0, sizeof(key));
  33. memset(hashes, 0, sizeof(hashes));
  34. /* Hash keys of the form {0}, {0,1}, {0,1,2}... up to N=255,using 256-N as
  35. the seed */
  36. for (i = 0; i < 256; i++) {
  37. key[i] = static_cast<uint8_t>(i);
  38. hashes[i] = hash(key, i, static_cast<uint32_t>(256u - i));
  39. }
  40. /* Then hash the result array */
  41. final = hash(hashes, sizeof(hashes), 0);
  42. /* The first four bytes of that hash, interpreted as a little-endian integer,
  43. is our
  44. verification value */
  45. if (expected != final) {
  46. gpr_log(GPR_INFO, "Verification value 0x%08X : Failed! (Expected 0x%08x)",
  47. final, expected);
  48. abort();
  49. } else {
  50. gpr_log(GPR_INFO, "Verification value 0x%08X : Passed!", final);
  51. }
  52. }
  53. int main(int argc, char** argv) {
  54. grpc::testing::TestEnvironment env(argc, argv);
  55. /* basic tests to verify that things don't crash */
  56. gpr_murmur_hash3("", 0, 0);
  57. gpr_murmur_hash3("xyz", 3, 0);
  58. verification_test(gpr_murmur_hash3, 0xB0F57EE3);
  59. return 0;
  60. }