1//===-- Unittests for memcmp ----------------------------------------------===//
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 "memory_utils/memory_check_utils.h"
10#include "src/string/memcmp.h"
11#include "test/UnitTest/Test.h"
12#include "test/UnitTest/TestLogger.h"
13
14namespace LIBC_NAMESPACE {
15
16TEST(LlvmLibcMemcmpTest, CmpZeroByte) {
17 const char *lhs = "ab";
18 const char *rhs = "yz";
19 EXPECT_EQ(LIBC_NAMESPACE::memcmp(lhs, rhs, 0), 0);
20}
21
22TEST(LlvmLibcMemcmpTest, LhsRhsAreTheSame) {
23 const char *lhs = "ab";
24 const char *rhs = "ab";
25 EXPECT_EQ(LIBC_NAMESPACE::memcmp(lhs, rhs, 2), 0);
26}
27
28TEST(LlvmLibcMemcmpTest, LhsBeforeRhsLexically) {
29 const char *lhs = "ab";
30 const char *rhs = "az";
31 EXPECT_LT(LIBC_NAMESPACE::memcmp(lhs, rhs, 2), 0);
32}
33
34TEST(LlvmLibcMemcmpTest, LhsAfterRhsLexically) {
35 const char *lhs = "az";
36 const char *rhs = "ab";
37 EXPECT_GT(LIBC_NAMESPACE::memcmp(lhs, rhs, 2), 0);
38}
39
40TEST(LlvmLibcMemcmpTest, Issue77080) {
41 // https://github.com/llvm/llvm-project/issues/77080
42 constexpr char lhs[35] = "1.069cd68bbe76eb2143a3284d27ebe220";
43 constexpr char rhs[35] = "1.0500185b5d966a544e2d0fa40701b0f3";
44 ASSERT_GE(LIBC_NAMESPACE::memcmp(lhs, rhs, 34), 1);
45}
46
47// Adapt CheckMemcmp signature to memcmp.
48static inline int Adaptor(cpp::span<char> p1, cpp::span<char> p2, size_t size) {
49 return LIBC_NAMESPACE::memcmp(lhs: p1.begin(), rhs: p2.begin(), count: size);
50}
51
52TEST(LlvmLibcMemcmpTest, SizeSweep) {
53 static constexpr size_t kMaxSize = 400;
54 Buffer Buffer1(kMaxSize);
55 Buffer Buffer2(kMaxSize);
56 Randomize(buffer: Buffer1.span());
57 for (size_t size = 0; size < kMaxSize; ++size) {
58 auto span1 = Buffer1.span().subspan(offset: 0, count: size);
59 auto span2 = Buffer2.span().subspan(offset: 0, count: size);
60 const bool OK = CheckMemcmp<Adaptor>(span1, span2, size);
61 if (!OK)
62 testing::tlog << "Failed at size=" << size << '\n';
63 ASSERT_TRUE(OK);
64 }
65}
66
67} // namespace LIBC_NAMESPACE
68

source code of libc/test/src/string/memcmp_test.cpp