xref: /aosp_15_r20/external/llvm-libc/test/src/math/smoke/CopySignTest.h (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
1 //===-- Utility class to test copysign[f|l] ---------------------*- 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 #ifndef LLVM_LIBC_TEST_SRC_MATH_SMOKE_COPYSIGNTEST_H
10 #define LLVM_LIBC_TEST_SRC_MATH_SMOKE_COPYSIGNTEST_H
11 
12 #include "src/__support/CPP/algorithm.h"
13 #include "test/UnitTest/FEnvSafeTest.h"
14 #include "test/UnitTest/FPMatcher.h"
15 #include "test/UnitTest/Test.h"
16 
17 #include "hdr/math_macros.h"
18 
19 template <typename T>
20 class CopySignTest : public LIBC_NAMESPACE::testing::FEnvSafeTest {
21 
22   DECLARE_SPECIAL_CONSTANTS(T)
23 
24 public:
25   typedef T (*CopySignFunc)(T, T);
26 
testSpecialNumbers(CopySignFunc func)27   void testSpecialNumbers(CopySignFunc func) {
28     EXPECT_FP_EQ(aNaN, func(aNaN, T(-1.0)));
29     EXPECT_FP_EQ(aNaN, func(aNaN, T(1.0)));
30 
31     EXPECT_FP_EQ(neg_inf, func(inf, T(-1.0)));
32     EXPECT_FP_EQ(inf, func(neg_inf, T(1.0)));
33 
34     EXPECT_FP_EQ(neg_zero, func(zero, T(-1.0)));
35     EXPECT_FP_EQ(zero, func(neg_zero, T(1.0)));
36   }
37 
testRange(CopySignFunc func)38   void testRange(CopySignFunc func) {
39     constexpr int COUNT = 100'000;
40     constexpr StorageType STEP = LIBC_NAMESPACE::cpp::max(
41         static_cast<StorageType>(STORAGE_MAX / COUNT), StorageType(1));
42     StorageType v = 0;
43     for (int i = 0; i <= COUNT; ++i, v += STEP) {
44       FPBits x_bits = FPBits(v);
45       if (x_bits.is_nan() || x_bits.is_inf())
46         continue;
47       T x = x_bits.get_val();
48 
49       T res1 = func(x, -x);
50       ASSERT_FP_EQ(res1, -x);
51 
52       T res2 = func(x, x);
53       ASSERT_FP_EQ(res2, x);
54     }
55   }
56 };
57 
58 #define LIST_COPYSIGN_TESTS(T, func)                                           \
59   using LlvmLibcCopySignTest = CopySignTest<T>;                                \
60   TEST_F(LlvmLibcCopySignTest, SpecialNumbers) { testSpecialNumbers(&func); }  \
61   TEST_F(LlvmLibcCopySignTest, Range) { testRange(&func); }
62 
63 #endif // LLVM_LIBC_TEST_SRC_MATH_SMOKE_COPYSIGNTEST_H
64