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