test_range.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include <iostream>
  2. #include <cassert>
  3. #include <limits>
  4. #include <boost/safe_numerics/utility.hpp>
  5. #include <boost/safe_numerics/safe_integer_range.hpp>
  6. template<typename T>
  7. void display_log(T Max){
  8. std::cout
  9. << "ilog2(" << Max << ") = "
  10. << boost::safe_numerics::utility::ilog2(Max) << std::endl;
  11. }
  12. bool test_significant_bits(){
  13. using namespace boost::safe_numerics;
  14. assert(utility::significant_bits(127u) == 7); // 7 bits
  15. assert(utility::significant_bits(127u) == 7); // 7 bits
  16. assert(utility::significant_bits(128u) == 8); // 8 bits
  17. assert(utility::significant_bits(129u) == 8); // 8 bits
  18. assert(utility::significant_bits(255u) == 8); // 8 bits
  19. assert(utility::significant_bits(256u) == 9); // 9 bits
  20. return true;
  21. }
  22. bool test1(){
  23. using namespace boost::safe_numerics;
  24. using t2 = safe_unsigned_range<0u, 1000u>;
  25. static_assert(
  26. std::numeric_limits<t2>::is_signed == false,
  27. "this range should be unsigned"
  28. );
  29. return true;
  30. }
  31. #include <boost/safe_numerics/automatic.hpp>
  32. template <
  33. std::intmax_t Min,
  34. std::intmax_t Max
  35. >
  36. using safe_t = boost::safe_numerics::safe_signed_range<
  37. Min,
  38. Max,
  39. boost::safe_numerics::automatic,
  40. boost::safe_numerics::default_exception_policy
  41. >;
  42. bool test2(){
  43. std::cout << "test1" << std::endl;
  44. try{
  45. const safe_t<-64, 63> x(1);
  46. safe_t<-64, 63> y;
  47. y = 2;
  48. std::cout << "x = " << x << std::endl;
  49. std::cout << "y = " << y << std::endl;
  50. auto z = x + y;
  51. std::cout << "x + y = ["
  52. << std::numeric_limits<decltype(z)>::min() << ","
  53. << std::numeric_limits<decltype(z)>::max() << "] = "
  54. << z << std::endl;
  55. auto z2 = x - y;
  56. std::cout << "x - y = ["
  57. << std::numeric_limits<decltype(z2)>::min() << ","
  58. << std::numeric_limits<decltype(z2)>::max() << "] = "
  59. << z2 << std::endl;
  60. short int yi, zi;
  61. yi = y;
  62. zi = x + yi;
  63. }
  64. catch(const std::exception & e){
  65. // none of the above should trap. Mark failure if they do
  66. std::cout << e.what() << std::endl;
  67. return false;
  68. }
  69. return true;
  70. }
  71. int main(){
  72. //using namespace boost::safe_numerics;
  73. //safe_signed_literal2<100> one_hundred;
  74. //one_hundred = 200;
  75. bool rval =
  76. test_significant_bits() &&
  77. test1() &&
  78. test2() /* &&
  79. test3() &&
  80. test4()
  81. */
  82. ;
  83. std::cout << (rval ? "success!" : "failure") << std::endl;
  84. return rval ? EXIT_SUCCESS : EXIT_FAILURE;
  85. }