md5_constexpr_unittest.cc 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2019 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 "base/hash/md5_constexpr.h"
  5. #include "base/hash/md5.h"
  6. #include "testing/gtest/include/gtest/gtest.h"
  7. namespace base {
  8. namespace internal {
  9. // Provide storage for the various constants, allowing the functions to be used
  10. // at runtime for these tests.
  11. constexpr std::array<uint32_t, 64> MD5CE::kConstants;
  12. constexpr std::array<uint32_t, 16> MD5CE::kShifts;
  13. constexpr MD5CE::IntermediateData MD5CE::kInitialIntermediateData;
  14. } // namespace internal
  15. // A constexpr comparison operator for MD5Results, allowing compile time tests
  16. // to be expressed.
  17. constexpr bool Equal(const MD5Digest& lhs, const MD5Digest& rhs) {
  18. for (size_t i = 0; i < std::size(lhs.a); ++i) {
  19. if (lhs.a[i] != rhs.a[i])
  20. return false;
  21. }
  22. return true;
  23. }
  24. // Ensure that everything works at compile-time by comparing to a few
  25. // reference hashes.
  26. constexpr char kMessage0[] = "message digest";
  27. static_assert(MD5Hash64Constexpr(kMessage0) == 0xF96B697D7CB7938Dull,
  28. "incorrect MD5Hash64 implementation");
  29. static_assert(MD5Hash32Constexpr(kMessage0) == 0xF96B697Dul,
  30. "incorrect MD5Hash32 implementation");
  31. constexpr char kMessage1[] = "The quick brown fox jumps over the lazy dog";
  32. static_assert(MD5Hash64Constexpr(kMessage1, std::size(kMessage1) - 1) ==
  33. 0x9E107D9D372BB682ull,
  34. "incorrect MD5Hash64 implementation");
  35. static_assert(MD5Hash32Constexpr(kMessage1, std::size(kMessage1) - 1) ==
  36. 0x9E107D9Dul,
  37. "incorrect MD5Hash32 implementation");
  38. // Comparison operator for checking that the constexpr MD5 implementation
  39. // matches the default implementation.
  40. void ExpectEqual(const MD5Digest& lhs, const MD5Digest& rhs) {
  41. for (size_t i = 0; i < std::size(lhs.a); ++i)
  42. EXPECT_EQ(lhs.a[i], rhs.a[i]);
  43. }
  44. } // namespace base