abs.pass.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //===----------------------------------------------------------------------===//
  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. #include <assert.h>
  9. #include <cmath>
  10. #include <cstdint>
  11. #include <limits>
  12. #include <type_traits>
  13. #include "test_macros.h"
  14. template<class T>
  15. struct correct_size_int
  16. {
  17. typedef typename std::conditional<sizeof(T) < sizeof(int), int, T>::type type;
  18. };
  19. template <class Source, class Result>
  20. void test_abs()
  21. {
  22. Source neg_val = -5;
  23. Source pos_val = 5;
  24. Result res = 5;
  25. ASSERT_SAME_TYPE(decltype(std::abs(neg_val)), Result);
  26. assert(std::abs(neg_val) == res);
  27. assert(std::abs(pos_val) == res);
  28. }
  29. void test_big()
  30. {
  31. long long int big_value = std::numeric_limits<long long int>::max(); // a value to big for ints to store
  32. long long int negative_big_value = -big_value;
  33. assert(std::abs(negative_big_value) == big_value); // make sure it doesnt get casted to a smaller type
  34. }
  35. // The following is helpful to keep in mind:
  36. // 1byte == char <= short <= int <= long <= long long
  37. int main(int, char**)
  38. {
  39. // On some systems char is unsigned.
  40. // If that is the case, we should just test signed char twice.
  41. typedef typename std::conditional<
  42. std::is_signed<char>::value, char, signed char
  43. >::type SignedChar;
  44. // All types less than or equal to and not greater than int are promoted to int.
  45. test_abs<short int, int>();
  46. test_abs<SignedChar, int>();
  47. test_abs<signed char, int>();
  48. // These three calls have specific overloads:
  49. test_abs<int, int>();
  50. test_abs<long int, long int>();
  51. test_abs<long long int, long long int>();
  52. // Here there is no guarantee that int is larger than int8_t so we
  53. // use a helper type trait to conditional test against int.
  54. test_abs<std::int8_t, typename correct_size_int<std::int8_t>::type>();
  55. test_abs<std::int16_t, typename correct_size_int<std::int16_t>::type>();
  56. test_abs<std::int32_t, typename correct_size_int<std::int32_t>::type>();
  57. test_abs<std::int64_t, typename correct_size_int<std::int64_t>::type>();
  58. test_abs<long double, long double>();
  59. test_abs<double, double>();
  60. test_abs<float, float>();
  61. test_big();
  62. return 0;
  63. }