1 /* boost random/detail/signed_unsigned_tools.hpp header file
3 * Copyright Jens Maurer 2006
4 * Distributed under the Boost Software License, Version 1.0. (See
5 * accompanying file LICENSE_1_0.txt or copy at
6 * http://www.boost.org/LICENSE_1_0.txt)
8 * See http://www.boost.org for most recent version including documentation.
11 #ifndef BOOST_RANDOM_DETAIL_SIGNED_UNSIGNED_TOOLS
12 #define BOOST_RANDOM_DETAIL_SIGNED_UNSIGNED_TOOLS
14 #include <boost/limits.hpp>
15 #include <boost/config.hpp>
16 #include <boost/type_traits/make_unsigned.hpp>
24 * Compute x - y, we know that x >= y, return an unsigned value.
27 template<class T, bool sgn = std::numeric_limits<T>::is_signed>
31 struct subtract<T, /* signed */ false>
33 typedef T result_type;
34 result_type operator()(T x, T y) { return x - y; }
38 struct subtract<T, /* signed */ true>
40 typedef typename make_unsigned<T>::type result_type;
41 result_type operator()(T x, T y)
43 if (y >= 0) // because x >= y, it follows that x >= 0, too
44 return result_type(x) - result_type(y);
46 // avoid the nasty two's complement case for y == min()
47 return result_type(x) + result_type(-(y+1)) + 1;
48 // both x and y are negative: no signed overflow
49 return result_type(x - y);
54 * Compute x + y, x is unsigned, result fits in type of "y".
57 template<class T1, class T2, bool sgn = std::numeric_limits<T2>::is_signed>
60 template<class T1, class T2>
61 struct add<T1, T2, /* signed */ false>
63 typedef T2 result_type;
64 result_type operator()(T1 x, T2 y) { return T2(x) + y; }
67 template<class T1, class T2>
68 struct add<T1, T2, /* signed */ true>
70 typedef T2 result_type;
71 result_type operator()(T1 x, T2 y)
76 if (x > T1(-(y+1))) // result >= 0 after subtraction
77 // avoid the nasty two's complement edge case for y == min()
78 return T2(x - T1(-(y+1)) - 1);
79 // abs(x) < abs(y), thus T2 able to represent x
88 #endif // BOOST_RANDOM_DETAIL_SIGNED_UNSIGNED_TOOLS