test_checked_xor_constexpr.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 <iostream>
  7. #include <boost/core/demangle.hpp>
  8. #include <boost/safe_numerics/checked_result_operations.hpp>
  9. #include <boost/safe_numerics/checked_integer.hpp>
  10. // note: T should be of tyme checked_result<R> for some integer type R
  11. template<class T>
  12. constexpr bool test_checked_xor(
  13. const T & v1,
  14. const T & v2,
  15. char expected_result
  16. ){
  17. using namespace boost::safe_numerics;
  18. const T result = v1 ^ v2;
  19. switch(expected_result){
  20. case '.':
  21. if(result.exception()){
  22. return false;
  23. }
  24. return true;
  25. case '-':
  26. if(safe_numerics_error::negative_overflow_error == result.m_e)
  27. return true;
  28. case '+':
  29. if(safe_numerics_error::positive_overflow_error == result.m_e)
  30. return true;
  31. case '!':
  32. if(safe_numerics_error::range_error == result.m_e)
  33. return true;
  34. }
  35. return false;
  36. }
  37. #include "test_checked_xor.hpp"
  38. template<typename T, typename First, typename Second>
  39. struct test_signed_pair {
  40. static const std::size_t i = First();
  41. static const std::size_t j = Second();
  42. static const bool value = test_checked_xor(
  43. signed_values<T>[i],
  44. signed_values<T>[j],
  45. signed_xor_results[i][j]
  46. );
  47. };
  48. template<typename T, typename First, typename Second>
  49. struct test_unsigned_pair {
  50. static const std::size_t i = First();
  51. static const std::size_t j = Second();
  52. // note: is constexpr really required here? compilers disagree!
  53. constexpr static const bool value = test_checked_xor(
  54. unsigned_values<T>[i],
  55. unsigned_values<T>[j],
  56. unsigned_xor_results[i][j]
  57. );
  58. };
  59. #include "check_symmetry.hpp"
  60. #include <boost/mp11/algorithm.hpp>
  61. int main(){
  62. using namespace boost::mp11;
  63. check_symmetry(signed_xor_results);
  64. check_symmetry(unsigned_xor_results);
  65. static_assert(
  66. mp_all_of<
  67. mp_product<
  68. test_signed_pair,
  69. signed_test_types,
  70. signed_value_indices, signed_value_indices
  71. >,
  72. mp_to_bool
  73. >(),
  74. "all values for all signed types correctly xor'ed"
  75. );
  76. static_assert(
  77. mp_all_of<
  78. mp_product<
  79. test_unsigned_pair,
  80. unsigned_test_types,
  81. unsigned_value_indices, unsigned_value_indices
  82. >,
  83. mp_to_bool
  84. >(),
  85. "all values for all unsigned types correctly xor'ed"
  86. );
  87. return 0;
  88. }