From ea704ae2cbd049c3db021bbb6f0e25f623ce1526 Mon Sep 17 00:00:00 2001
From: David Wells <drwells@email.unc.edu>
Date: Sun, 11 Aug 2024 14:08:11 -0600
Subject: [PATCH] PetscWrappers::MatrixBase: add index conversion checks.

---
 include/deal.II/lac/petsc_matrix_base.h |  2 +-
 source/lac/petsc_matrix_base.cc         | 32 +++++++++++++++++++++----
 2 files changed, 28 insertions(+), 6 deletions(-)

diff --git a/include/deal.II/lac/petsc_matrix_base.h b/include/deal.II/lac/petsc_matrix_base.h
index 599255ad29..9aef393564 100644
--- a/include/deal.II/lac/petsc_matrix_base.h
+++ b/include/deal.II/lac/petsc_matrix_base.h
@@ -1480,7 +1480,7 @@ namespace PETScWrappers
 
     prepare_action(VectorOperation::add);
 
-    const auto petsc_row = row;
+    const auto petsc_row = static_cast<PetscInt>(row);
     AssertIntegerConversion(petsc_row, row);
 
     PetscInt n_columns = 0;
diff --git a/source/lac/petsc_matrix_base.cc b/source/lac/petsc_matrix_base.cc
index d4afe87756..17ca8ae366 100644
--- a/source/lac/petsc_matrix_base.cc
+++ b/source/lac/petsc_matrix_base.cc
@@ -59,6 +59,13 @@ namespace PETScWrappers
       // iterator for an empty line (what
       // would it point to?)
       Assert(ncols != 0, ExcInternalError());
+#    ifdef DEBUG
+      for (PetscInt j = 0; j < ncols; ++j)
+        {
+          const auto column = static_cast<PetscInt>(colnums[j]);
+          AssertIntegerConversion(column, colnums[j]);
+        }
+#    endif
       colnum_cache =
         std::make_shared<std::vector<size_type>>(colnums, colnums + ncols);
       value_cache =
@@ -157,8 +164,14 @@ namespace PETScWrappers
   {
     assert_is_compressed();
 
-    // now set all the entries of these rows
-    // to zero
+    // now set all the entries of these rows to zero
+#  ifdef DEBUG
+    for (size_type i = 0; i < rows.size(); ++i)
+      {
+        const auto row = static_cast<PetscInt>(rows[i]);
+        AssertIntegerConversion(row, rows[i]);
+      }
+#  endif
     const std::vector<PetscInt> petsc_rows(rows.begin(), rows.end());
 
     // call the functions. note that we have
@@ -186,8 +199,14 @@ namespace PETScWrappers
   {
     assert_is_compressed();
 
-    // now set all the entries of these rows
-    // to zero
+    // now set all the entries of these rows to zero
+#  ifdef DEBUG
+    for (size_type i = 0; i < rows.size(); ++i)
+      {
+        const auto row = static_cast<PetscInt>(rows[i]);
+        AssertIntegerConversion(row, rows[i]);
+      }
+#  endif
     const std::vector<PetscInt> petsc_rows(rows.begin(), rows.end());
 
     // call the functions. note that we have
@@ -215,7 +234,10 @@ namespace PETScWrappers
   PetscScalar
   MatrixBase::el(const size_type i, const size_type j) const
   {
-    PetscInt petsc_i = i, petsc_j = j;
+    const auto petsc_i = static_cast<PetscInt>(i);
+    AssertIntegerConversion(petsc_i, i);
+    const auto petsc_j = static_cast<PetscInt>(j);
+    AssertIntegerConversion(petsc_j, j);
 
     PetscScalar value;
 
-- 
2.39.5