1
0
Fork 0
mirror of https://github.com/bolero-MURAKAMI/Sprout synced 2024-11-12 21:09:01 +00:00
Sprout/sprout/utility/limited.hpp

47 lines
1.8 KiB
C++
Raw Normal View History

#ifndef SPROUT_INTEGER_LIMITED_HPP
#define SPROUT_INTEGER_LIMITED_HPP
#include <sprout/config.hpp>
2013-08-06 15:15:09 +00:00
#include <sprout/limits.hpp>
#include <sprout/type_traits/arithmetic_promote.hpp>
namespace sprout {
namespace limited {
//
// plus
//
template<typename T, typename U>
inline SPROUT_CONSTEXPR typename sprout::arithmetic_promote<T, U>::type
plus(T const& lhs, U const& rhs) {
typedef typename sprout::arithmetic_promote<T, U>::type type;
2013-08-06 15:15:09 +00:00
return lhs > 0 && rhs > 0 && sprout::numeric_limits<type>::max() - lhs < rhs
? sprout::numeric_limits<type>::max()
: lhs < 0 && rhs < 0 && sprout::numeric_limits<type>::min() - lhs > rhs
? sprout::numeric_limits<type>::min()
: lhs + rhs
;
}
//
// multiplies
//
template<typename T, typename U>
inline SPROUT_CONSTEXPR typename sprout::arithmetic_promote<T, U>::type
multiplies(T const& lhs, U const& rhs) {
typedef typename sprout::arithmetic_promote<T, U>::type type;
2013-08-06 15:15:09 +00:00
return lhs > 0 && rhs > 0 && sprout::numeric_limits<type>::max() / lhs + (sprout::numeric_limits<type>::max() % lhs ? 1 : 0) <= rhs
? sprout::numeric_limits<type>::max()
: lhs > 0 && rhs < 0 && sprout::numeric_limits<type>::min() / rhs + (sprout::numeric_limits<type>::min() % rhs ? 1 : 0) <= lhs
? sprout::numeric_limits<type>::min()
: lhs < 0 && rhs > 0 && sprout::numeric_limits<type>::min() / lhs + (sprout::numeric_limits<type>::min() % lhs ? 1 : 0) <= rhs
? sprout::numeric_limits<type>::min()
: lhs < 0 && rhs < 0 && -(sprout::numeric_limits<type>::min() / rhs + (sprout::numeric_limits<type>::min() % rhs ? 1 : 0)) >= lhs
? sprout::numeric_limits<type>::max()
: lhs * rhs
;
}
} // namespace limited
} // namespace sprout
#endif // #ifndef SPROUT_INTEGER_LIMITED_HPP