Skip to content

Commit 81db745

Browse files
authored
Fix integer overflow when creating a large matrix (#81)
* Convert to long to avoid overflow when calculating the product m * n * Add new test case for creating a large matrix without throwing an exception
1 parent e064ecf commit 81db745

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

src/main/java/com/ustermetrics/clarabel4j/Matrix.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ public record Matrix(int m, int n, long @NonNull [] colPtr, long @NonNull [] row
3232
checkArgument(nnz == rowVal.length, "length of data must be equal to the length of the row index");
3333
checkArgument(colPtr.length == n + 1,
3434
"length of the column index must be equal to the number of columns plus one");
35-
checkArgument(nnz <= m * n,
35+
checkArgument(nnz <= (long) m * n,
3636
"number of non-zero entries must be less equal than the number of rows times the number of columns");
3737
checkArgument(Arrays.stream(rowVal).allMatch(i -> 0 <= i && i < m),
3838
"entries of the row index must be greater equal zero and less than the number of rows");

src/test/java/com/ustermetrics/clarabel4j/MatrixTest.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import lombok.val;
44
import org.junit.jupiter.api.Test;
55

6+
import java.util.Arrays;
7+
68
import static org.junit.jupiter.api.Assertions.*;
79

810
class MatrixTest {
@@ -125,4 +127,14 @@ void createMatrixWithUnorderedRowIndexWithinColumnThrowsException() {
125127
assertEquals("entries of the row index within each column must be strictly ordered", exception.getMessage());
126128
}
127129

130+
@Test
131+
void createLargeMatrixDoesNotThrowException() {
132+
val m = 46341;
133+
val colPtr = new long[m + 1];
134+
Arrays.fill(colPtr, 1, m + 1, 1);
135+
assertDoesNotThrow(() ->
136+
new Matrix(m, m, colPtr, new long[]{0}, new double[]{1.})
137+
);
138+
}
139+
128140
}

0 commit comments

Comments
 (0)