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 "src/__support/macros/config.h"
12 #include "test/UnitTest/Test.h"
13
14 #if LIBC_TEST_HAS_MATCHERS()
15
16 using LIBC_NAMESPACE::testing::tlog;
17
18 namespace LIBC_NAMESPACE_DECL {
19 namespace testing {
20
21 template <typename T>
equals(const cpp::span<T> & Span1,const cpp::span<T> & Span2,bool & mismatch_size,size_t & mismatch_index)22 bool equals(const cpp::span<T> &Span1, const cpp::span<T> &Span2,
23 bool &mismatch_size, size_t &mismatch_index) {
24 if (Span1.size() != Span2.size()) {
25 mismatch_size = true;
26 return false;
27 }
28 for (size_t Index = 0; Index < Span1.size(); ++Index)
29 if (Span1[Index] != Span2[Index]) {
30 mismatch_index = Index;
31 return false;
32 }
33 return true;
34 }
35
match(MemoryView actualValue)36 bool MemoryMatcher::match(MemoryView actualValue) {
37 actual = actualValue;
38 return equals(expected, actual, mismatch_size, mismatch_index);
39 }
40
display(char C)41 static void display(char C) {
42 const auto print = [](unsigned char I) {
43 tlog << static_cast<char>(I < 10 ? '0' + I : 'A' + I - 10);
44 };
45 print(static_cast<unsigned char>(C) / 16);
46 print(static_cast<unsigned char>(C) & 15);
47 }
48
display(MemoryView View)49 static void display(MemoryView View) {
50 for (auto C : View) {
51 tlog << ' ';
52 display(C);
53 }
54 }
55
explainError()56 void MemoryMatcher::explainError() {
57 if (mismatch_size) {
58 tlog << "Size mismatch :";
59 tlog << "expected : ";
60 tlog << expected.size();
61 tlog << '\n';
62 tlog << "actual : ";
63 tlog << actual.size();
64 tlog << '\n';
65 } else {
66 tlog << "Mismatch at position : ";
67 tlog << mismatch_index;
68 tlog << " / ";
69 tlog << expected.size();
70 tlog << "\n";
71 tlog << "expected :";
72 display(expected);
73 tlog << '\n';
74 tlog << "actual :";
75 display(actual);
76 tlog << '\n';
77 }
78 }
79
80 } // namespace testing
81 } // namespace LIBC_NAMESPACE_DECL
82
83 #endif // LIBC_TEST_HAS_MATCHERS()
84