From: David Wells <drwells@email.unc.edu>
Date: Sun, 11 Aug 2024 19:13:35 +0000 (-0600)
Subject: IndexSet::make_petsc_is(): assert indices are in range.
X-Git-Url: https://gitweb.dealii.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=7d152c7e59afedddaace5b0eadda463c1541096c;p=dealii.git

IndexSet::make_petsc_is(): assert indices are in range.
---

diff --git a/source/base/index_set.cc b/source/base/index_set.cc
index 35d91f9217..66885684ec 100644
--- a/source/base/index_set.cc
+++ b/source/base/index_set.cc
@@ -1112,12 +1112,20 @@ IndexSet::make_petsc_is(const MPI_Comm communicator) const
   std::vector<size_type> indices;
   fill_index_vector(indices);
 
-  PetscInt              n = indices.size();
-  std::vector<PetscInt> pindices(indices.begin(), indices.end());
+  // If the size of the index set can be converted to a PetscInt then every
+  // value can also be converted
+  AssertThrowIntegerConversion(static_cast<PetscInt>(size()), size());
+  const auto local_size = static_cast<PetscInt>(n_elements());
+  AssertIntegerConversion(local_size, n_elements());
+
+  size_type             i = 0;
+  std::vector<PetscInt> petsc_indices(n_elements());
+  for (const auto &index : *this)
+    petsc_indices[i] = static_cast<PetscInt>(index);
 
   IS             is;
-  PetscErrorCode ierr =
-    ISCreateGeneral(communicator, n, pindices.data(), PETSC_COPY_VALUES, &is);
+  PetscErrorCode ierr = ISCreateGeneral(
+    communicator, local_size, petsc_indices.data(), PETSC_COPY_VALUES, &is);
   AssertThrow(ierr == 0, ExcPETScError(ierr));
 
   return is;