Skip to content

Commit

Permalink
fix: negative numbers in json parser
Browse files Browse the repository at this point in the history
  • Loading branch information
erdos committed Oct 13, 2021
1 parent d375ee7 commit 27bb9da
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
4 changes: 2 additions & 2 deletions java-src/io/github/erdos/stencil/standalone/JsonParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ private static Object simpleParse(PushbackReader pb) throws IOException {
} else if (c == 'n') {
expectWord("null", pb);
return null;
} else if (Character.isDigit(c)) {
} else if (Character.isDigit(c) || c == '+' || c == '-') {
return readNumber(pb);
} else {
throw new IllegalStateException("Unexpected character: '" + c + "'");
Expand All @@ -69,7 +69,7 @@ static Number readNumber(PushbackReader pb) throws IOException {
char[] arr = new char[128];
int len = pb.read(arr, 0, arr.length);

assert Character.isDigit(arr[0]);
assert arr[0] == '+' || arr[0] == '-' || Character.isDigit(arr[0]);

int i = 0;
while (i < len && (arr[i] == '.' || arr[i] == '-' || arr[i] == 'e' || Character.isDigit(arr[i]))) {
Expand Down
19 changes: 19 additions & 0 deletions java-test/io/github/erdos/stencil/standalone/JsonParserTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,25 @@ public void readNumberTest2() throws IOException {
assertEquals((Character) 'x', (Character) (char) pbr.read());
}

@Test
public void readNumberNegativeTest() throws IOException {
final String input = "-3";
PushbackReader pbr = pbr(input);

final Number result = JsonParser.readNumber(pbr);
assertEquals(new BigDecimal("-3"), result);
}

@Test
@SuppressWarnings("unchecked")
public void readMapWithNegativeValue() throws IOException {
String input = "{\n" + " \"test\": -3\n" + "}";
PushbackReader pbr = pbr(input);

Map<String, Object> result = (Map<String, Object>) JsonParser.read(pbr);
assertEquals(new BigDecimal("-3"), result.get("test"));
}

@Test
public void readScalarsTest() throws IOException {
assertEquals(true, JsonParser.read(pbr("true")));
Expand Down

0 comments on commit 27bb9da

Please sign in to comment.