[libcxx-commits] [libcxx] [libc++][numeric] P0543R3: Saturation arithmetic (PR #77967)

Mark de Wever via libcxx-commits libcxx-commits at lists.llvm.org
Sat Jan 13 05:24:45 PST 2024


================
@@ -0,0 +1,98 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20, c++23
+
+// <numeric>
+
+// template<class T>
+// constexpr T add_sat(T x, T y) noexcept;                     // freestanding
+
+#include <cassert>
+#include <concepts>
+#include <limits>
+#include <numeric>
+
+template <typename IntegerT>
+constexpr bool test_signed() {
+  constexpr auto minVal = std::numeric_limits<IntegerT>::min();
+  constexpr auto maxVal = std::numeric_limits<IntegerT>::max();
+
+  static_assert(noexcept(std::div_sat(minVal, maxVal)));
+
+  // No saturation
+  {
+    std::same_as<IntegerT> decltype(auto) sum = std::add_sat(IntegerT{3}, IntegerT{4});
+    assert(sum == IntegerT{7});
+  }
+
+  {
+    std::same_as<IntegerT> decltype(auto) sum = std::add_sat(IntegerT{-3}, IntegerT{4});
+    assert(sum == IntegerT{1});
+  }
+
+  // Saturation - max - both arguments positive
+  {
+    std::same_as<IntegerT> decltype(auto) sum = std::add_sat(maxVal, IntegerT{4});
----------------
mordante wrote:

I would like to see a few more edge cases, -1, 0 , and 1. We should test with the maximum for both the `__x_` and the `__y`. I also like to see cases that overflow when 2 large numbers are added. For example 
__x = max() / 2 + 10
__x = max() / 2 + 5

https://github.com/llvm/llvm-project/pull/77967


More information about the libcxx-commits mailing list