From 20727a2b9124f4949bf0a83456036278d5ae4db5 Mon Sep 17 00:00:00 2001 From: Palash Tyagi <23239946+Magnus167@users.noreply.github.com> Date: Sat, 3 May 2025 00:25:45 +0100 Subject: [PATCH] Improve column swapping logic to handle empty matrices and prevent overlapping swaps --- src/matrix/mat.rs | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/matrix/mat.rs b/src/matrix/mat.rs index 82acb38..2b1c564 100644 --- a/src/matrix/mat.rs +++ b/src/matrix/mat.rs @@ -149,19 +149,24 @@ impl Matrix { self.cols ); if c1 == c2 { - // Indices are equal; no operation required return; } - // Iterate over each row to swap corresponding elements - for r in 0..self.rows { - // Compute the one-dimensional index for (row r, column c1) - let idx1 = c1 * self.rows + r; - // Compute the one-dimensional index for (row r, column c2) - let idx2 = c2 * self.rows + r; + if self.rows == 0 { + self.data.swap(c1, c2); + return; + } - // Exchange the two elements in the internal data buffer - self.data.swap(idx1, idx2); + let (start1, end1) = (c1 * self.rows, (c1 + 1) * self.rows); + let (start2, end2) = (c2 * self.rows, (c2 + 1) * self.rows); + + if (start1 < start2 && end1 > start2) || (start2 < start1 && end2 > start1) { + panic!("Cannot swap overlapping columns"); + } + + // element-wise swap + for r in 0..self.rows { + self.data.swap(start1 + r, start2 + r); } }