[llvm-profdata] Add SaturatingAdd/SaturatingMultiply Helper Functions
[oota-llvm.git] / unittests / Support / MathExtrasTest.cpp
index 8bd47e3..8adde02 100644 (file)
@@ -190,4 +190,52 @@ TEST(MathExtras, RoundUpToAlignment) {
   EXPECT_EQ(552u, RoundUpToAlignment(321, 255, 42));
 }
 
+template<typename T>
+void SaturatingAddTestHelper()
+{
+  EXPECT_EQ(static_cast<T>(3),
+            SaturatingAdd(static_cast<T>(1), static_cast<T>(2)));
+  EXPECT_EQ(std::numeric_limits<T>::max(),
+            SaturatingAdd(std::numeric_limits<T>::max(), static_cast<T>(1)));
+  EXPECT_EQ(std::numeric_limits<T>::max(),
+            SaturatingAdd(static_cast<T>(1), std::numeric_limits<T>::max()));
+  EXPECT_EQ(std::numeric_limits<T>::max(),
+            SaturatingAdd(std::numeric_limits<T>::max(),
+                          std::numeric_limits<T>::max()));
+}
+
+TEST(MathExtras, SaturatingAdd) {
+  SaturatingAddTestHelper<uint8_t>();
+  SaturatingAddTestHelper<uint16_t>();
+  SaturatingAddTestHelper<uint32_t>();
+  SaturatingAddTestHelper<uint64_t>();
+}
+
+template<typename T>
+void SaturatingMultiplyTestHelper()
+{
+  EXPECT_EQ(static_cast<T>(0),
+            SaturatingMultiply(static_cast<T>(1), static_cast<T>(0)));
+  EXPECT_EQ(static_cast<T>(0),
+            SaturatingMultiply(static_cast<T>(0), static_cast<T>(1)));
+  EXPECT_EQ(static_cast<T>(6),
+            SaturatingMultiply(static_cast<T>(2), static_cast<T>(3)));
+  EXPECT_EQ(std::numeric_limits<T>::max(),
+            SaturatingMultiply(std::numeric_limits<T>::max(),
+                               static_cast<T>(2)));
+  EXPECT_EQ(std::numeric_limits<T>::max(),
+            SaturatingMultiply(static_cast<T>(2),
+                               std::numeric_limits<T>::max()));
+  EXPECT_EQ(std::numeric_limits<T>::max(),
+            SaturatingMultiply(std::numeric_limits<T>::max(),
+                          std::numeric_limits<T>::max()));
+}
+
+TEST(MathExtras, SaturatingMultiply) {
+  SaturatingMultiplyTestHelper<uint8_t>();
+  SaturatingMultiplyTestHelper<uint16_t>();
+  SaturatingMultiplyTestHelper<uint32_t>();
+  SaturatingMultiplyTestHelper<uint64_t>();
+}
+
 }