ChecksumTest.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright 2012 Google Inc.
  3. *
  4. * Use of this source code is governed by a BSD-style license that can be
  5. * found in the LICENSE file.
  6. */
  7. #include "include/core/SkTypes.h"
  8. #include "include/private/SkChecksum.h"
  9. #include "include/utils/SkRandom.h"
  10. #include "src/core/SkOpts.h"
  11. #include "tests/Test.h"
  12. DEF_TEST(Checksum, r) {
  13. // Put 128 random bytes into two identical buffers. Any multiple of 4 will do.
  14. const size_t kBytes = SkAlign4(128);
  15. SkRandom rand;
  16. uint32_t data[kBytes/4], tweaked[kBytes/4];
  17. for (size_t i = 0; i < SK_ARRAY_COUNT(tweaked); ++i) {
  18. data[i] = tweaked[i] = rand.nextU();
  19. }
  20. // Hash of nullptr is always 0.
  21. REPORTER_ASSERT(r, SkOpts::hash(nullptr, 0) == 0);
  22. const uint32_t hash = SkOpts::hash(data, kBytes);
  23. // Should be deterministic.
  24. REPORTER_ASSERT(r, hash == SkOpts::hash(data, kBytes));
  25. // Changing any single element should change the hash.
  26. for (size_t j = 0; j < SK_ARRAY_COUNT(tweaked); ++j) {
  27. const uint32_t saved = tweaked[j];
  28. tweaked[j] = rand.nextU();
  29. const uint32_t tweakedHash = SkOpts::hash(tweaked, kBytes);
  30. REPORTER_ASSERT(r, tweakedHash != hash);
  31. REPORTER_ASSERT(r, tweakedHash == SkOpts::hash(tweaked, kBytes));
  32. tweaked[j] = saved;
  33. }
  34. }
  35. DEF_TEST(GoodHash, r) {
  36. // 4 bytes --> hits SkChecksum::Mix fast path.
  37. REPORTER_ASSERT(r, SkGoodHash()(( int32_t)4) == 614249093);
  38. REPORTER_ASSERT(r, SkGoodHash()((uint32_t)4) == 614249093);
  39. }
  40. DEF_TEST(ChecksumCollisions, r) {
  41. // We noticed a few workloads that would cause hash collisions due to the way
  42. // our optimized hashes split into three concurrent hashes and merge those hashes together.
  43. //
  44. // One of these two workloads ought to cause an unintentional hash collision on very similar
  45. // data in those old algorithms, the float version on 32-bit x86 and double elsewhere.
  46. {
  47. float a[9] = { 0, 1, 2,
  48. 3, 4, 5,
  49. 6, 7, 8, };
  50. float b[9] = { 1, 2, 0,
  51. 4, 5, 3,
  52. 7, 8, 6, };
  53. REPORTER_ASSERT(r, SkOpts::hash(a, sizeof(a)) != SkOpts::hash(b, sizeof(b)));
  54. }
  55. {
  56. double a[9] = { 0, 1, 2,
  57. 3, 4, 5,
  58. 6, 7, 8, };
  59. double b[9] = { 1, 2, 0,
  60. 4, 5, 3,
  61. 7, 8, 6, };
  62. REPORTER_ASSERT(r, SkOpts::hash(a, sizeof(a)) != SkOpts::hash(b, sizeof(b)));
  63. }
  64. }