| 1 | //===-- Utility class to test int to fixed point conversions ----*- 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 "test/UnitTest/Test.h" |
| 10 | |
| 11 | #include "include/llvm-libc-types/stdfix-types.h" |
| 12 | #include "src/__support/CPP/bit.h" |
| 13 | #include "src/__support/fixed_point/fx_bits.h" |
| 14 | |
| 15 | template <typename T, typename XType> |
| 16 | class FxBitsTest : public LIBC_NAMESPACE::testing::Test { |
| 17 | using FXRep = LIBC_NAMESPACE::fixed_point::FXRep<T>; |
| 18 | static constexpr T zero = FXRep::ZERO(); |
| 19 | static constexpr T min = FXRep::MIN(); |
| 20 | static constexpr T max = FXRep::MAX(); |
| 21 | static constexpr T half = static_cast<T>(0.5); |
| 22 | static constexpr T quarter = static_cast<T>(0.25); |
| 23 | static constexpr T one = |
| 24 | (FXRep::INTEGRAL_LEN > 0) ? static_cast<T>(1) : FXRep::MAX(); |
| 25 | static constexpr T eps = FXRep::EPS(); |
| 26 | constexpr XType get_one_or_saturated_fraction() { |
| 27 | if (FXRep::INTEGRAL_LEN > 0) { |
| 28 | return static_cast<XType>(static_cast<XType>(0x1) << FXRep::FRACTION_LEN); |
| 29 | } else { |
| 30 | return static_cast<XType>( |
| 31 | LIBC_NAMESPACE::mask_trailing_ones<typename FXRep::StorageType, |
| 32 | FXRep::FRACTION_LEN>()); |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | public: |
| 37 | typedef T (*FxBitsFunc)(XType); |
| 38 | |
| 39 | void test_special_numbers(FxBitsFunc func) { |
| 40 | EXPECT_EQ(zero, func(0)); |
| 41 | EXPECT_EQ(eps, func(0x1)); |
| 42 | // x.1000... |
| 43 | EXPECT_EQ(half, func(static_cast<XType>(0x1) << (FXRep::FRACTION_LEN - 1))); |
| 44 | // Occupy the bit to the left of the fixed point for Accum types |
| 45 | // Saturate fraction portion for Fract types |
| 46 | EXPECT_EQ(one, func(get_one_or_saturated_fraction())); |
| 47 | } |
| 48 | }; |
| 49 | |
| 50 | #define LIST_FXBITS_TEST(Name, T, XType, func) \ |
| 51 | using LlvmLibc##Name##BitsTest = FxBitsTest<T, XType>; \ |
| 52 | TEST_F(LlvmLibc##Name##BitsTest, SpecialNumbers) { \ |
| 53 | test_special_numbers(&func); \ |
| 54 | } \ |
| 55 | static_assert(true, "Require semicolon.") |
| 56 | |