1 | //===-- MemoryMatcher.cpp ---------------------------------------*- C++ -*-===// |
---|---|
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | |
9 | #include "MemoryMatcher.h" |
10 | |
11 | #include "test/UnitTest/Test.h" |
12 | |
13 | #if LIBC_TEST_HAS_MATCHERS() |
14 | |
15 | using LIBC_NAMESPACE::testing::tlog; |
16 | |
17 | namespace LIBC_NAMESPACE { |
18 | namespace testing { |
19 | |
20 | template <typename T> |
21 | bool equals(const cpp::span<T> &Span1, const cpp::span<T> &Span2, |
22 | bool &mismatch_size, size_t &mismatch_index) { |
23 | if (Span1.size() != Span2.size()) { |
24 | mismatch_size = true; |
25 | return false; |
26 | } |
27 | for (size_t Index = 0; Index < Span1.size(); ++Index) |
28 | if (Span1[Index] != Span2[Index]) { |
29 | mismatch_index = Index; |
30 | return false; |
31 | } |
32 | return true; |
33 | } |
34 | |
35 | bool MemoryMatcher::match(MemoryView actualValue) { |
36 | actual = actualValue; |
37 | return equals(Span1: expected, Span2: actual, mismatch_size, mismatch_index); |
38 | } |
39 | |
40 | static void display(char C) { |
41 | const auto print = [](unsigned char I) { |
42 | tlog << static_cast<char>(I < 10 ? '0' + I : 'A' + I - 10); |
43 | }; |
44 | print(static_cast<unsigned char>(C) / 16); |
45 | print(static_cast<unsigned char>(C) & 15); |
46 | } |
47 | |
48 | static void display(MemoryView View) { |
49 | for (auto C : View) { |
50 | tlog << ' '; |
51 | display(C); |
52 | } |
53 | } |
54 | |
55 | void MemoryMatcher::explainError() { |
56 | if (mismatch_size) { |
57 | tlog << "Size mismatch :"; |
58 | tlog << "expected : "; |
59 | tlog << expected.size(); |
60 | tlog << '\n'; |
61 | tlog << "actual : "; |
62 | tlog << actual.size(); |
63 | tlog << '\n'; |
64 | } else { |
65 | tlog << "Mismatch at position : "; |
66 | tlog << mismatch_index; |
67 | tlog << " / "; |
68 | tlog << expected.size(); |
69 | tlog << "\n"; |
70 | tlog << "expected :"; |
71 | display(View: expected); |
72 | tlog << '\n'; |
73 | tlog << "actual :"; |
74 | display(View: actual); |
75 | tlog << '\n'; |
76 | } |
77 | } |
78 | |
79 | } // namespace testing |
80 | } // namespace LIBC_NAMESPACE |
81 | |
82 | #endif // LIBC_TEST_HAS_MATCHERS() |
83 |