Add coefficient-wise modulus operator (%) for Array

libeigen/eigen!2307

Closes #2837

Co-authored-by: Pavel Guzenfeld <35347582-PavelGuzenfeld@users.noreply.gitlab.com>
diff --git a/Eigen/src/Core/functors/BinaryFunctors.h b/Eigen/src/Core/functors/BinaryFunctors.h
index baccca9..2bbed74 100644
--- a/Eigen/src/Core/functors/BinaryFunctors.h
+++ b/Eigen/src/Core/functors/BinaryFunctors.h
@@ -494,6 +494,31 @@
 // rely on this invariant.
 
 /** \internal
+ * \brief Template functor to compute the modulus of two integer scalars
+ *
+ * \sa class CwiseBinaryOp, ArrayBase::operator%()
+ */
+template <typename LhsScalar, typename RhsScalar>
+struct scalar_modulus_op : binary_op_base<LhsScalar, RhsScalar> {
+  using result_type = typename ScalarBinaryOpTraits<LhsScalar, RhsScalar, scalar_modulus_op>::ReturnType;
+  static constexpr bool Enable = std::is_same<LhsScalar, RhsScalar>::value && NumTraits<LhsScalar>::IsInteger;
+  EIGEN_STATIC_ASSERT(Enable, "LhsScalar and RhsScalar must be the same integer type")
+#ifdef EIGEN_SCALAR_BINARY_OP_PLUGIN
+  scalar_modulus_op(){EIGEN_SCALAR_BINARY_OP_PLUGIN}
+#endif
+  EIGEN_DEVICE_FUNC constexpr EIGEN_STRONG_INLINE result_type
+  operator()(const LhsScalar& a, const RhsScalar& b) const {
+    return a % b;
+  }
+};
+template <typename LhsScalar, typename RhsScalar>
+struct functor_traits<scalar_modulus_op<LhsScalar, RhsScalar>> {
+  using result_type = typename scalar_modulus_op<LhsScalar, RhsScalar>::result_type;
+  static constexpr bool PacketAccess = false;
+  static constexpr int Cost = scalar_div_cost<result_type, false>::value;
+};
+
+/** \internal
  * \brief Template functor to compute the and of two scalars as if they were booleans
  *
  * \sa class CwiseBinaryOp, ArrayBase::operator&&
diff --git a/Eigen/src/plugins/ArrayCwiseBinaryOps.inc b/Eigen/src/plugins/ArrayCwiseBinaryOps.inc
index fee9ed7..907d03b 100644
--- a/Eigen/src/plugins/ArrayCwiseBinaryOps.inc
+++ b/Eigen/src/plugins/ArrayCwiseBinaryOps.inc
@@ -24,6 +24,42 @@
                        const OtherDerived>(derived(), other.derived());
 }
 
+/** \returns an expression of the coefficient-wise modulus of \c *this and \a other
+ *
+ * \note This operator is for integer scalar types only. A zero divisor is undefined behavior, as for the built-in
+ * modulus operator.
+ *
+ * Example: \code
+ * Array3i a(7, 8, 9), b(2, 3, 4);
+ * cout << a % b << endl;  // prints 1 2 1
+ * \endcode
+ *
+ * \sa operator/()
+ */
+template <typename OtherDerived>
+EIGEN_DEVICE_FUNC constexpr EIGEN_STRONG_INLINE const
+    CwiseBinaryOp<internal::scalar_modulus_op<Scalar, typename OtherDerived::Scalar>, const Derived, const OtherDerived>
+    operator%(const EIGEN_CURRENT_STORAGE_BASE_CLASS<OtherDerived> &other) const {
+  return CwiseBinaryOp<internal::scalar_modulus_op<Scalar, typename OtherDerived::Scalar>, const Derived,
+                       const OtherDerived>(derived(), other.derived());
+}
+
+EIGEN_MAKE_SCALAR_BINARY_OP_ONTHERIGHT(operator%, internal::scalar_modulus_op)
+
+#ifndef EIGEN_PARSED_BY_DOXYGEN
+EIGEN_MAKE_SCALAR_BINARY_OP_ONTHELEFT(operator%, internal::scalar_modulus_op)
+#else
+/**
+ * \brief Component-wise modulus of the scalar \a s by array elements of \a a.
+ *
+ * \tparam T is the scalar type of \a s. It must be compatible with the scalar type of the given array expression
+ * (\c Derived::Scalar).
+ */
+template <typename T>
+friend inline const CwiseBinaryOp<internal::scalar_modulus_op<T, Scalar>, Constant<T>, Derived> operator%(
+    const T &s, const StorageBaseType &a);
+#endif
+
 /** \returns an expression of the coefficient-wise min of \c *this and \a other
  *
  * Example: \include Cwise_min.cpp
diff --git a/failtest/CMakeLists.txt b/failtest/CMakeLists.txt
index 57c4bd3..c42e6b6 100644
--- a/failtest/CMakeLists.txt
+++ b/failtest/CMakeLists.txt
@@ -92,6 +92,8 @@
 ei_add_failtest("vandermonde_rectangular_square")
 ei_add_failtest("bjorckpereyra_rectangular")
 
+ei_add_failtest("array_modulus_float")
+
 ei_add_failtest("structured_bindings_dynamic_matrix")
 ei_add_failtest("structured_bindings_dynamic_array")
 ei_add_failtest("structured_bindings_rowmajor")
diff --git a/failtest/array_modulus_float.cpp b/failtest/array_modulus_float.cpp
new file mode 100644
index 0000000..87467e4
--- /dev/null
+++ b/failtest/array_modulus_float.cpp
@@ -0,0 +1,18 @@
+#include "../Eigen/Core"
+
+#ifdef EIGEN_SHOULD_FAIL_TO_BUILD
+#define SCALAR float
+#else
+#define SCALAR int
+#endif
+
+using namespace Eigen;
+
+// Only forms the expression; the functor's static_assert is what must reject a
+// float scalar, since operator() is never instantiated here.
+int main() {
+  ArrayX<SCALAR> a = ArrayX<SCALAR>::Ones(4), b = ArrayX<SCALAR>::Ones(4);
+  auto expr = a % b;
+  (void)expr;
+  return 0;
+}
diff --git a/test/array_cwise.cpp b/test/array_cwise.cpp
index b1ce0f2..df6066e 100644
--- a/test/array_cwise.cpp
+++ b/test/array_cwise.cpp
@@ -1590,6 +1590,69 @@
   }
 }
 
+// Coefficient-wise modulus. Integer scalars only.
+// Original coverage by @arvsrao in !1705; extended here to the array-array form,
+// the scalar-on-the-left form, negative operands, and the 2D and compound-expression cases.
+template <typename Scalar>
+void modulus_test_impl() {
+  // Array % Array, 1D.
+  Array<Scalar, 3, 1> a(Scalar(7), Scalar(8), Scalar(9));
+  Array<Scalar, 3, 1> b(Scalar(2), Scalar(3), Scalar(4));
+  Array<Scalar, 3, 1> expected(Scalar(1), Scalar(2), Scalar(1));
+  VERIFY_IS_CWISE_EQUAL(a % b, expected);
+
+  // Array % scalar.
+  Array<Scalar, 3, 1> a_mod_2(Scalar(1), Scalar(0), Scalar(1));
+  VERIFY_IS_CWISE_EQUAL(a % Scalar(2), a_mod_2);
+
+  // Scalar % Array.
+  Array<Scalar, 3, 1> ten_mod_b(Scalar(0), Scalar(1), Scalar(2));
+  VERIFY_IS_CWISE_EQUAL(Scalar(10) % b, ten_mod_b);
+
+  // Modulus of a compound expression.
+  // (7,8,9) + (2,3,4) = (9,11,13); mod 4 -> (1,3,1)
+  Array<Scalar, 3, 1> compound(Scalar(1), Scalar(3), Scalar(1));
+  VERIFY_IS_CWISE_EQUAL((a + b) % Scalar(4), compound);
+
+  // Dynamic 2D.
+  ArrayXX<Scalar> m(2, 3);
+  m << Scalar(0), Scalar(1), Scalar(2), Scalar(3), Scalar(4), Scalar(5);
+  ArrayXX<Scalar> m_mod_3(2, 3);
+  m_mod_3 << Scalar(0), Scalar(1), Scalar(2), Scalar(0), Scalar(1), Scalar(2);
+  VERIFY_IS_CWISE_EQUAL(m % Scalar(3), m_mod_3);
+  VERIFY_IS_CWISE_EQUAL(m % ArrayXX<Scalar>::Constant(2, 3, Scalar(3)), m_mod_3);
+
+  // Agreement with the scalar operator, including negative dividends where the
+  // sign of the result follows the dividend (C++11 onwards).
+  if (NumTraits<Scalar>::IsSigned) {
+    Array<Scalar, 4, 1> neg(Scalar(-7), Scalar(-1), Scalar(7), Scalar(0));
+    Array<Scalar, 4, 1> div(Scalar(3), Scalar(3), Scalar(-3), Scalar(3));
+    for (Index i = 0; i < neg.size(); ++i) {
+      VERIFY_IS_EQUAL((neg % div)(i), Scalar(neg(i) % div(i)));
+    }
+  }
+
+  // Matches a hand-rolled loop over random data.
+  ArrayX<Scalar> lhs = ArrayX<Scalar>::Random(37);
+  ArrayX<Scalar> rhs = ArrayX<Scalar>::Random(37);
+  rhs = (rhs == Scalar(0) || rhs == Scalar(-1)).select(ArrayX<Scalar>::Constant(37, Scalar(1)), rhs);
+  ArrayX<Scalar> got = lhs % rhs;
+  for (Index i = 0; i < lhs.size(); ++i) {
+    VERIFY_IS_EQUAL(got(i), Scalar(lhs(i) % rhs(i)));
+  }
+}
+
+void modulus_tests() {
+  modulus_test_impl<int8_t>();
+  modulus_test_impl<int16_t>();
+  modulus_test_impl<int>();
+  modulus_test_impl<int64_t>();
+  modulus_test_impl<uint8_t>();
+  modulus_test_impl<uint16_t>();
+  modulus_test_impl<uint32_t>();
+  modulus_test_impl<uint64_t>();
+}
+
 EIGEN_DECLARE_TEST(array_cwise) {
   for (int i = 0; i < g_repeat; i++) {
     CALL_SUBTEST_1(array_generic(Array<float, 1, 1>()));
@@ -1689,6 +1752,7 @@
     CALL_SUBTEST_26(typed_logicals_test(ArrayX<std::complex<float>>(internal::random<int>(1, EIGEN_TEST_MAX_SIZE))));
     CALL_SUBTEST_27(typed_logicals_test(ArrayX<std::complex<double>>(internal::random<int>(1, EIGEN_TEST_MAX_SIZE))));
     CALL_SUBTEST_42(bool_logical_ops<>());
+    CALL_SUBTEST_43(modulus_tests());
   }
 
   for (int i = 0; i < g_repeat; i++) {