test_checked_modulus_constexpr.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright (c) 2018 Robert Ramey
  2. //
  3. // Distributed under the Boost Software License, Version 1.0. (See
  4. // accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. #include <boost/safe_numerics/checked_result.hpp>
  7. #include <boost/safe_numerics/checked_result_operations.hpp>
  8. #include <boost/safe_numerics/checked_integer.hpp>
  9. template<class T>
  10. constexpr bool test_checked_modulus(
  11. const T & v1,
  12. const T & v2,
  13. char expected_result
  14. ){
  15. using namespace boost::safe_numerics;
  16. const T result = v1 % v2;
  17. switch(expected_result){
  18. case '0':
  19. case '.':
  20. return ! result.exception();
  21. case '-':
  22. return safe_numerics_error::negative_overflow_error == result.m_e;
  23. case '+':
  24. return safe_numerics_error::positive_overflow_error == result.m_e;
  25. case '!':
  26. return safe_numerics_error::range_error == result.m_e;
  27. }
  28. return false;
  29. }
  30. #include "test_checked_modulus.hpp"
  31. #include <boost/mp11/algorithm.hpp>
  32. template<typename T, typename First, typename Second>
  33. struct test_signed_pair {
  34. static const std::size_t i = First();
  35. static const std::size_t j = Second();
  36. // note: is constexpr really required here? compilers disagree!
  37. constexpr static const bool value = test_checked_modulus(
  38. signed_values<T>[i],
  39. signed_values<T>[j],
  40. signed_modulus_results[i][j]
  41. );
  42. };
  43. template<typename T, typename First, typename Second>
  44. struct test_unsigned_pair {
  45. static const std::size_t i = First();
  46. static const std::size_t j = Second();
  47. // note: is constexpr really required here? compilers disagree!
  48. constexpr static const bool value = test_checked_modulus(
  49. unsigned_values<T>[i],
  50. unsigned_values<T>[j],
  51. unsigned_modulus_results[i][j]
  52. );
  53. };
  54. #include <boost/mp11/algorithm.hpp>
  55. #include <boost/mp11/function.hpp>
  56. int main(){
  57. using namespace boost::mp11;
  58. static_assert(
  59. mp_all_of<
  60. mp_product<
  61. test_signed_pair,
  62. signed_test_types,
  63. signed_value_indices, signed_value_indices
  64. >,
  65. mp_to_bool
  66. >(),
  67. "modulus for all signed values correct"
  68. );
  69. static_assert(
  70. mp_all_of<
  71. mp_product<
  72. test_unsigned_pair,
  73. unsigned_test_types,
  74. unsigned_value_indices, unsigned_value_indices
  75. >,
  76. mp_to_bool
  77. >(),
  78. "modulus for all unsigned values correct"
  79. );
  80. return 0;
  81. }