test_checked_and_constexpr.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. // note: T should be of tyme checked_result<R> for some integer type R
  10. template<class T>
  11. constexpr bool test_checked_and(
  12. const T & v1,
  13. const T & v2,
  14. char expected_result
  15. ){
  16. using namespace boost::safe_numerics;
  17. const T result = v1 & v2;
  18. switch(expected_result){
  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_and.hpp"
  31. template<typename T, typename First, typename Second>
  32. struct test_signed_pair {
  33. static const std::size_t i = First();
  34. static const std::size_t j = Second();
  35. // note: is constexpr really required here? compilers disagree!
  36. constexpr static const bool value = test_checked_and(
  37. signed_values<T>[i],
  38. signed_values<T>[j],
  39. signed_and_results[i][j]
  40. );
  41. };
  42. template<typename T, typename First, typename Second>
  43. struct test_unsigned_pair {
  44. static const std::size_t i = First();
  45. static const std::size_t j = Second();
  46. // note: is constexpr really required here? compilers disagree!
  47. constexpr static const bool value = test_checked_and(
  48. unsigned_values<T>[i],
  49. unsigned_values<T>[j],
  50. unsigned_and_results[i][j]
  51. );
  52. };
  53. #include "check_symmetry.hpp"
  54. #include <boost/mp11/algorithm.hpp>
  55. int main(){
  56. using namespace boost::mp11;
  57. check_symmetry(signed_and_results);
  58. check_symmetry(unsigned_and_results);
  59. static_assert(
  60. mp_all_of<
  61. mp_product<
  62. test_signed_pair,
  63. signed_test_types,
  64. signed_value_indices, signed_value_indices
  65. >,
  66. mp_to_bool
  67. >(),
  68. "all values for all signed types correctly anded"
  69. );
  70. static_assert(
  71. mp_all_of<
  72. mp_product<
  73. test_unsigned_pair,
  74. unsigned_test_types,
  75. unsigned_value_indices, unsigned_value_indices
  76. >,
  77. mp_to_bool
  78. >(),
  79. "all values for all unsigned types correctly anded"
  80. );
  81. return 0;
  82. }