2 // Copyright 2012 John Maddock. Distributed under the Boost
3 // Software License, Version 1.0. (See accompanying file
4 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_
6 #ifndef BOOST_MP_CPP_INT_CHECKED_HPP
7 #define BOOST_MP_CPP_INT_CHECKED_HPP
9 namespace boost{ namespace multiprecision{ namespace backends{ namespace detail{
12 // Simple routines for performing checked arithmetic with a builtin arithmetic type.
13 // Note that this is not a complete header, it must be included as part of boost/multiprecision/cpp_int.hpp.
16 inline void raise_overflow(std::string op)
18 BOOST_THROW_EXCEPTION(std::overflow_error("overflow in " + op));
20 inline void raise_add_overflow()
22 raise_overflow("addition");
24 inline void raise_subtract_overflow()
26 BOOST_THROW_EXCEPTION(std::range_error("Subtraction resulted in a negative value, but the type is unsigned"));
28 inline void raise_mul_overflow()
30 raise_overflow("multiplication");
32 inline void raise_div_overflow()
34 raise_overflow("division");
38 inline A checked_add_imp(A a, A b, const mpl::true_&)
42 if((b > 0) && ((integer_traits<A>::const_max - b) < a))
47 if((b < 0) && ((integer_traits<A>::const_min - b) > a))
53 inline A checked_add_imp(A a, A b, const mpl::false_&)
55 if((integer_traits<A>::const_max - b) < a)
60 inline A checked_add(A a, A b, const mpl::int_<checked>&)
62 return checked_add_imp(a, b, boost::is_signed<A>());
65 inline A checked_add(A a, A b, const mpl::int_<unchecked>&)
71 inline A checked_subtract_imp(A a, A b, const mpl::true_&)
75 if((b < 0) && ((integer_traits<A>::const_max + b) < a))
76 raise_subtract_overflow();
80 if((b > 0) && ((integer_traits<A>::const_min + b) > a))
81 raise_subtract_overflow();
86 inline A checked_subtract_imp(A a, A b, const mpl::false_&)
89 raise_subtract_overflow();
93 inline A checked_subtract(A a, A b, const mpl::int_<checked>&)
95 return checked_subtract_imp(a, b, boost::is_signed<A>());
98 inline A checked_subtract(A a, A b, const mpl::int_<unchecked>&)
104 inline A checked_multiply(A a, A b, const mpl::int_<checked>&)
107 if(a && (integer_traits<A>::const_max / abs(a) < abs(b)))
108 raise_mul_overflow();
112 inline A checked_multiply(A a, A b, const mpl::int_<unchecked>&)
118 inline A checked_divide(A a, A b, const mpl::int_<checked>&)
121 raise_div_overflow();
125 inline A checked_divide(A a, A b, const mpl::int_<unchecked>&)
131 inline A checked_left_shift(A a, boost::ulong_long_type shift, const mpl::int_<checked>&)
135 if((shift > sizeof(A) * CHAR_BIT) || (a >> (sizeof(A) * CHAR_BIT - shift)))
136 BOOST_THROW_EXCEPTION(std::overflow_error("Shift out of range"));
141 inline A checked_left_shift(A a, boost::ulong_long_type shift, const mpl::int_<unchecked>&)
143 return (shift >= sizeof(A) * CHAR_BIT) ? 0 : a << shift;