Advertisement
Guest User

Untitled

a guest
Nov 19th, 2015
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. #include <limits>
  2. #include <type_traits>
  3.  
  4. #include <assert.h>
  5. #include <stdint.h>
  6.  
  7. /// \brief Multiply two unsigned integers, X and Y, of type T.
  8. /// Clamp the result to the maximum representable value of T on overflow.
  9. #if 0
  10. template <typename T>
  11. typename std::enable_if<std::is_unsigned<T>::value, T>::type
  12. SaturatingMultiply(T X, T Y) {
  13.   const T Max = std::numeric_limits<T>::max();
  14.   if (Y != 0 && X >= Max / Y) {
  15.     return Max;
  16.   } else {
  17.     return X * Y;
  18.   }
  19. }
  20. #else
  21. template <typename T>
  22. typename std::enable_if<std::is_unsigned<T>::value, T>::type
  23. SaturatingMultiply(T X, T Y) {
  24.   // Hacker's Delight, p. 30
  25.   T Z = X * Y;
  26.   if (Y != 0 && Z / Y != X)
  27.     return std::numeric_limits<T>::max();
  28.   else
  29.     return Z;
  30. }
  31. #endif
  32.  
  33. #define EXPECT_EQ(x, y) assert(x == y)
  34.  
  35. template<typename T>
  36. void SaturatingMultiplyTestHelper()
  37. {
  38.   const T Max = std::numeric_limits<T>::max();
  39.   EXPECT_EQ(T(0), SaturatingMultiply(T(1), T(0)));
  40.   EXPECT_EQ(T(0), SaturatingMultiply(T(0), T(1)));
  41.   EXPECT_EQ(T(6), SaturatingMultiply(T(2), T(3)));
  42.   EXPECT_EQ(Max, SaturatingMultiply(Max, T(2)));
  43.   EXPECT_EQ(Max, SaturatingMultiply(T(2),Max));
  44.   EXPECT_EQ(Max, SaturatingMultiply(Max, Max));
  45. }
  46.  
  47. int main()
  48. {
  49.   SaturatingMultiplyTestHelper<uint8_t>();
  50.   SaturatingMultiplyTestHelper<uint16_t>();
  51.   SaturatingMultiplyTestHelper<uint32_t>();
  52.   SaturatingMultiplyTestHelper<uint64_t>();
  53.  
  54.   return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement