Skip to content

Commit 8a940bf

Browse files
authored
Fix off-by-one rejecting trailing nan/infinity in parseNumber (#326)
Add round-trip and imaginary-part special value parse tests
1 parent 4e14c08 commit 8a940bf

2 files changed

Lines changed: 30 additions & 1 deletion

File tree

commons-math-legacy/src/main/java/org/apache/commons/math4/legacy/util/CompositeFormat.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ private static Number parseNumber(final String source, final double value,
117117
final int n = sb.length();
118118
final int startIndex = pos.getIndex();
119119
final int endIndex = startIndex + n;
120-
if (endIndex < source.length() &&
120+
if (endIndex <= source.length() &&
121121
source.substring(startIndex, endIndex).compareTo(sb.toString()) == 0) {
122122
ret = Double.valueOf(value);
123123
pos.setIndex(endIndex);

commons-math-legacy/src/test/java/org/apache/commons/math4/legacy/util/ComplexFormatAbstractTest.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,35 @@ public void testPaseNegativeInfinity() {
277277
Assert.assertEquals(expected, actual);
278278
}
279279

280+
@Test
281+
public void testParseRealNan() {
282+
// a real-only special value runs to the last character of the string
283+
Complex expected = Complex.ofCartesian(Double.NaN, 0);
284+
Assert.assertEquals(expected, complexFormat.parse("(NaN)"));
285+
Assert.assertEquals(expected, complexFormat.parse(complexFormat.format(expected)));
286+
}
287+
288+
@Test
289+
public void testParseRealInfinity() {
290+
Complex positive = Complex.ofCartesian(Double.POSITIVE_INFINITY, 0);
291+
Assert.assertEquals(positive, complexFormat.parse("(Infinity)"));
292+
Assert.assertEquals(positive, complexFormat.parse(complexFormat.format(positive)));
293+
Complex negative = Complex.ofCartesian(Double.NEGATIVE_INFINITY, 0);
294+
Assert.assertEquals(negative, complexFormat.parse("(-Infinity)"));
295+
Assert.assertEquals(negative, complexFormat.parse(complexFormat.format(negative)));
296+
}
297+
298+
@Test
299+
public void testParseImaginarySpecialValue() {
300+
// the special value sits in the imaginary part, ahead of the imaginary character
301+
Complex nan = Complex.ofCartesian(1.23, Double.NaN);
302+
Assert.assertEquals(nan, complexFormat.parse(complexFormat.format(nan)));
303+
Complex positive = Complex.ofCartesian(1.23, Double.POSITIVE_INFINITY);
304+
Assert.assertEquals(positive, complexFormat.parse(complexFormat.format(positive)));
305+
Complex negative = Complex.ofCartesian(1.23, Double.NEGATIVE_INFINITY);
306+
Assert.assertEquals(negative, complexFormat.parse(complexFormat.format(negative)));
307+
}
308+
280309
@Test
281310
public void testConstructorSingleFormat() {
282311
NumberFormat nf = NumberFormat.getInstance();

0 commit comments

Comments
 (0)