Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <limits>
- #include <type_traits>
- #include <assert.h>
- #include <stdint.h>
- /// \brief Multiply two unsigned integers, X and Y, of type T.
- /// Clamp the result to the maximum representable value of T on overflow.
- #if 0
- template <typename T>
- typename std::enable_if<std::is_unsigned<T>::value, T>::type
- SaturatingMultiply(T X, T Y) {
- const T Max = std::numeric_limits<T>::max();
- if (Y != 0 && X >= Max / Y) {
- return Max;
- } else {
- return X * Y;
- }
- }
- #else
- template <typename T>
- typename std::enable_if<std::is_unsigned<T>::value, T>::type
- SaturatingMultiply(T X, T Y) {
- // Hacker's Delight, p. 30
- T Z = X * Y;
- if (Y != 0 && Z / Y != X)
- return std::numeric_limits<T>::max();
- else
- return Z;
- }
- #endif
- #define EXPECT_EQ(x, y) assert(x == y)
- template<typename T>
- void SaturatingMultiplyTestHelper()
- {
- const T Max = std::numeric_limits<T>::max();
- EXPECT_EQ(T(0), SaturatingMultiply(T(1), T(0)));
- EXPECT_EQ(T(0), SaturatingMultiply(T(0), T(1)));
- EXPECT_EQ(T(6), SaturatingMultiply(T(2), T(3)));
- EXPECT_EQ(Max, SaturatingMultiply(Max, T(2)));
- EXPECT_EQ(Max, SaturatingMultiply(T(2),Max));
- EXPECT_EQ(Max, SaturatingMultiply(Max, Max));
- }
- int main()
- {
- SaturatingMultiplyTestHelper<uint8_t>();
- SaturatingMultiplyTestHelper<uint16_t>();
- SaturatingMultiplyTestHelper<uint32_t>();
- SaturatingMultiplyTestHelper<uint64_t>();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement