From 323b1e832a39033c8830097a19750aa1e39f0fef Mon Sep 17 00:00:00 2001 From: Morris Meyer Date: Sat, 21 Nov 2026 20:40:08 +0000 Subject: [PATCH 1/9] Compile JMH Scala sources for Java 21 so jmhJar builds on JDK 25 --- build.gradle | 2 ++ 1 file changed, 2 insertions(+) diff --git a/build.gradle b/build.gradle index 3609523..c191cfe 100644 --- a/build.gradle +++ b/build.gradle @@ -180,6 +180,8 @@ tasks.withType(JavaCompile).configureEach { } tasks.compileJmhScala.classpath = sourceSets.main.compileClasspath +// Scala 2.13.16 cannot emit class files for Java 25+, so the Scala benchmark sources target Java 21. +tasks.compileJmhScala.scalaCompileOptions.additionalParameters = ['-release:21'] tasks.compileJmhJava.classpath += files(sourceSets.jmh.scala.classesDirectory) compileTestJava { From f6e99017f2b74fb9083565614aa1e8bf9be3abad Mon Sep 17 00:00:00 2001 From: Morris Meyer Date: Sat, 21 Nov 2026 20:40:08 +0000 Subject: [PATCH 2/9] Make test256 and test512 run the test suite on Gradle 9 Gradle 9 no longer sets testClassesDirs and classpath for Test tasks registered by the build, so test256 and test512 reported NO-SOURCE and ran no tests at all. Point both tasks at the test source set, as the built-in test task is. --- build.gradle | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/build.gradle b/build.gradle index c191cfe..a01f9a2 100644 --- a/build.gradle +++ b/build.gradle @@ -157,6 +157,10 @@ test { // We use mustRunAfter so they don't interleave output if run together via 'check'. dependsOn tasks.named('test') + // Gradle 9 no longer wires custom Test tasks to the test source set. + testClassesDirs = sourceSets.test.output.classesDirs + classpath = sourceSets.test.runtimeClasspath + useJUnitPlatform() jvmArgs += [ '--add-modules', 'jdk.incubator.vector', From 2952252b5221be28b3032b655bc6a10c6ad9d0f6 Mon Sep 17 00:00:00 2001 From: Morris Meyer Date: Sat, 21 Nov 2026 20:40:08 +0000 Subject: [PATCH 3/9] schema-based parsing: accept integer literals for floating-point types Parsing an integer literal such as 5 into a float, Float, double or Double failed with "Invalid floating-point number. Fraction or exponent part is missing.", although it is a valid JSON number and real documents mix 5 and 5.0 for the same field. NumberParser.parseFloat/parseDouble now pass integer literals to the existing FloatParser/DoubleParser, which already round them exactly (fast path, Eisel-Lemire, and the slow path for more than 19 significant digits). All other validation is unchanged. The test integralNumberAsFloatingPointNumber asserted the old rejection; it is replaced by tests that expect Float.parseFloat/Double.parseDouble results at the root, in object fields, in arrays and in lists, plus tests that invalid integer literals are still rejected. Fixes #70. --- src/main/java/org/simdjson/NumberParser.java | 12 -- ...tingPointNumberSchemaBasedParsingTest.java | 198 +++++++++++++++++- 2 files changed, 195 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/simdjson/NumberParser.java b/src/main/java/org/simdjson/NumberParser.java index 44fab42..1c77f06 100644 --- a/src/main/java/org/simdjson/NumberParser.java +++ b/src/main/java/org/simdjson/NumberParser.java @@ -233,9 +233,7 @@ float parseFloat(byte[] buffer, int len, int offset) { } long exponent = 0; - boolean floatingPointNumber = false; if ('.' == buffer[currentIdx]) { - floatingPointNumber = true; currentIdx++; int firstIdxAfterPeriod = currentIdx; digitsParsingResult = parseDigits(buffer, currentIdx, digitsParsingResult.digits()); @@ -247,15 +245,11 @@ float parseFloat(byte[] buffer, int len, int offset) { digitCount = currentIdx - digitsStartIdx; } if (isExponentIndicator(buffer[currentIdx])) { - floatingPointNumber = true; currentIdx++; ExponentParsingResult exponentParsingResult = exponentParser.parse(buffer, currentIdx, exponent); exponent = exponentParsingResult.exponent(); currentIdx = exponentParsingResult.currentIdx(); } - if (!floatingPointNumber) { - throw new JsonParsingException("Invalid floating-point number. Fraction or exponent part is missing."); - } if (currentIdx < len && !isStructuralOrWhitespace(buffer[currentIdx])) { throw new JsonParsingException("Number has to be followed by a structural character or whitespace."); } @@ -280,9 +274,7 @@ float parseFloat(byte[] buffer, int len, int offset) { } long exponent = 0; - boolean floatingPointNumber = false; if ('.' == buffer[currentIdx]) { - floatingPointNumber = true; currentIdx++; int firstIdxAfterPeriod = currentIdx; digitsParsingResult = parseDigits(buffer, currentIdx, digitsParsingResult.digits()); @@ -294,15 +286,11 @@ float parseFloat(byte[] buffer, int len, int offset) { digitCount = currentIdx - digitsStartIdx; } if (isExponentIndicator(buffer[currentIdx])) { - floatingPointNumber = true; currentIdx++; ExponentParsingResult exponentParsingResult = exponentParser.parse(buffer, currentIdx, exponent); exponent = exponentParsingResult.exponent(); currentIdx = exponentParsingResult.currentIdx(); } - if (!floatingPointNumber) { - throw new JsonParsingException("Invalid floating-point number. Fraction or exponent part is missing."); - } if (currentIdx < len && !isStructuralOrWhitespace(buffer[currentIdx])) { throw new JsonParsingException("Number has to be followed by a structural character or whitespace."); } diff --git a/src/test/java/org/simdjson/FloatingPointNumberSchemaBasedParsingTest.java b/src/test/java/org/simdjson/FloatingPointNumberSchemaBasedParsingTest.java index 0315055..f956dc6 100644 --- a/src/test/java/org/simdjson/FloatingPointNumberSchemaBasedParsingTest.java +++ b/src/test/java/org/simdjson/FloatingPointNumberSchemaBasedParsingTest.java @@ -28,7 +28,9 @@ import org.simdjson.testutils.SchemaBasedRandomValueSource; import java.io.IOException; +import java.lang.reflect.Array; import java.math.BigDecimal; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -1235,8 +1237,123 @@ public void testFilesForFloat(FloatingPointNumberTestFile file) throws IOExcepti } @CartesianTest - public void integralNumberAsFloatingPointNumber( - @Values(strings = {"123", "0", "-123"}) String jsonStr, + public void integralNumberAsFloatingPointNumberAtRoot( + @CartesianTestCsv({ + "0", + "-0", + "123", + "-123", + "16777216", + "16777217", + "-16777217", + "9007199254740992", + "9007199254740993", + "-9007199254740993", + "9223372036854775807", + "-9223372036854775808", + "9999999999999999999", + "18446744073709551615", + "123456789012345678901234567890", + "-123456789012345678901234567890", + "1000000000000000000000000000000000000000" + }) CartesianTestCsvRow row, + @Values(classes = {float.class, Float.class, Double.class, double.class}) Class expectedType) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8(row.getValueAsString(0)); + + // when + Object value = parser.parse(json, json.length, expectedType); + + // then + assertThat(value).isEqualTo(row.getValue(0, expectedType)); + } + + @CartesianTest + public void integralNumberAsFloatingPointNumberAtObjectField( + @CartesianTestCsv({ + "0", + "-0", + "-123", + "16777217", + "9007199254740993", + "9223372036854775807", + "123456789012345678901234567890" + }) CartesianTestCsvRow row, + @Values(classes = { + RecordWithFloatField.class, + RecordWithPrimitiveFloatField.class, + RecordWithDoubleField.class, + RecordWithPrimitiveDoubleField.class + }) Class schema) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"field\": " + row.getValueAsString(0) + "}"); + Class fieldType = schema.getRecordComponents()[0].getType(); + + // when + Object object = parser.parse(json, json.length, schema); + + // then + assertThat(object).extracting("field").isEqualTo(row.getValue(0, fieldType)); + } + + @CartesianTest + public void integralNumbersInArrayOfFloatingPointNumbersAtRoot( + @CartesianTestCsv({ + "0", + "-0", + "-123", + "16777217", + "9007199254740993", + "9223372036854775807", + "123456789012345678901234567890" + }) CartesianTestCsvRow row, + @Values(classes = {float[].class, Float[].class, Double[].class, double[].class}) Class schema) { + // given + SimdJsonParser parser = new SimdJsonParser(); + String numberStr = row.getValueAsString(0); + byte[] json = toUtf8("[" + numberStr + ", " + numberStr + "]"); + Class elementType = schema.getComponentType(); + Object expected = Array.newInstance(elementType, 2); + Array.set(expected, 0, row.getValue(0, elementType)); + Array.set(expected, 1, row.getValue(0, elementType)); + + // when + Object array = parser.parse(json, json.length, schema); + + // then + assertThat(array).isEqualTo(expected); + } + + @CartesianTest + public void integralNumbersInListOfFloatingPointNumbersAtObjectField( + @CartesianTestCsv({ + "0", + "-0", + "-123", + "16777217", + "9007199254740993", + "9223372036854775807", + "123456789012345678901234567890" + }) CartesianTestCsvRow row, + @Values(classes = {RecordWithFloatListField.class, RecordWithDoubleListField.class}) Class schema) { + // given + SimdJsonParser parser = new SimdJsonParser(); + String numberStr = row.getValueAsString(0); + byte[] json = toUtf8("{\"field\": [" + numberStr + ", " + numberStr + "]}"); + Class elementType = schema == RecordWithFloatListField.class ? Float.class : Double.class; + + // when + Object object = parser.parse(json, json.length, schema); + + // then + assertThat(object).extracting("field").isEqualTo(List.of(row.getValue(0, elementType), row.getValue(0, elementType))); + } + + @CartesianTest + public void leadingZerosAreNotAllowedInIntegralNumber( + @Values(strings = {"00", "01", "-00", "-01", "0123"}) String jsonStr, @Values(classes = {float.class, Float.class, Double.class, double.class}) Class expectedType) { // given SimdJsonParser parser = new SimdJsonParser(); @@ -1247,7 +1364,82 @@ public void integralNumberAsFloatingPointNumber( // then assertThat(ex) - .hasMessage("Invalid floating-point number. Fraction or exponent part is missing."); + .hasMessage("Invalid number. Leading zeroes are not allowed."); + } + + @CartesianTest + public void minusHasToBeFollowedByAtLeastOneDigitInIntegralNumber( + @Values(strings = {"-", "-a1", "--1", "+1"}) String jsonStr, + @Values(classes = {float.class, Float.class, Double.class, double.class}) Class expectedType) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8(jsonStr); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, () -> parser.parse(json, json.length, expectedType)); + + // then + assertThat(ex) + .hasMessage("Invalid number. Minus has to be followed by a digit."); + } + + @CartesianTest + public void integralNumberHasToBeFollowedByStructuralCharacterOrWhitespace( + @Values(strings = {"1a", "-1-2", "12-3", "1-", "123456789012345678901234567890a"}) String jsonStr, + @Values(classes = {float.class, Float.class, Double.class, double.class}) Class expectedType) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8(jsonStr); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, () -> parser.parse(json, json.length, expectedType)); + + // then + assertThat(ex) + .hasMessage("Number has to be followed by a structural character or whitespace."); + } + + @CartesianTest + public void moreValuesThanOneIntegralNumberAtRoot( + @Values(strings = {"123,", "123{}", "1:", "1 2"}) String jsonStr, + @Values(classes = {float.class, Float.class, Double.class, double.class}) Class expectedType) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8(jsonStr); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, () -> parser.parse(json, json.length, expectedType)); + + // then + assertThat(ex) + .hasMessage("More than one JSON value at the root of the document, or extra characters at the end of the JSON!"); + } + + @CartesianTest + public void invalidIntegralNumberAtObjectField( + @CartesianTestCsv({ + "01, Invalid number. Leading zeroes are not allowed.", + "-01, Invalid number. Leading zeroes are not allowed.", + "-, Invalid number. Minus has to be followed by a digit.", + "1a, Number has to be followed by a structural character or whitespace.", + "1-2, Number has to be followed by a structural character or whitespace." + }) CartesianTestCsvRow row, + @Values(classes = { + RecordWithFloatField.class, + RecordWithPrimitiveFloatField.class, + RecordWithDoubleField.class, + RecordWithPrimitiveDoubleField.class + }) Class schema) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"field\": " + row.getValueAsString(0) + "}"); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, () -> parser.parse(json, json.length, schema)); + + // then + assertThat(ex) + .hasMessage(row.getValueAsString(1)); } @ParameterizedTest From 6c9d3d00441e59025092ebc6439a0f03e3bc115b Mon Sep 17 00:00:00 2001 From: Morris Meyer Date: Sat, 21 Nov 2026 20:40:08 +0000 Subject: [PATCH 4/9] Expose on-demand parsing through SimdJsonParser.parseOnDemand parseOnDemand runs stage 1 only and returns the parser's OnDemandJsonIterator, a forward-only cursor that decodes values when the caller asks for them and skips everything else, without building a tape. This lets callers that need a few fields of a large document read them without allocating per value. The cursor is the iterator that schema-based parsing already uses. Its navigation methods and its string, number and boolean getters become public, and it gains: - peekType(), the JSON type of the next value, taken from its first byte - peekOffset() and lastTokenOffset(), the byte span of a value - getRawNumber(byte[]), the verbatim number literal - STRING_BUFFER_PADDING, the room getString and getFieldName may write past the decoded string - a check that nothing follows the root object or array once it has been read to its end The class documentation describes the lifecycle, the string buffer contract and how getDepth() and skipChild(int) skip the rest of a container. --- src/main/java/org/simdjson/BitIndexes.java | 9 + .../org/simdjson/OnDemandJsonIterator.java | 448 ++++++- .../java/org/simdjson/SimdJsonParser.java | 26 + src/main/java/org/simdjson/StringParser.java | 3 + .../org/simdjson/OnDemandParsingTest.java | 1152 +++++++++++++++++ 5 files changed, 1613 insertions(+), 25 deletions(-) create mode 100644 src/test/java/org/simdjson/OnDemandParsingTest.java diff --git a/src/main/java/org/simdjson/BitIndexes.java b/src/main/java/org/simdjson/BitIndexes.java index 59c0dc3..0a5f295 100644 --- a/src/main/java/org/simdjson/BitIndexes.java +++ b/src/main/java/org/simdjson/BitIndexes.java @@ -57,6 +57,11 @@ int getLast() { return indexes[writeIdx - 1]; } + int lastIndex() { + assert readIdx > 0; + return indexes[readIdx - 1]; + } + int advanceAndGet() { assert readIdx + 1 <= writeIdx; return indexes[++readIdx]; @@ -71,6 +76,10 @@ boolean hasNext() { return writeIdx > readIdx; } + boolean isStart() { + return readIdx == 0; + } + boolean isEnd() { return writeIdx == readIdx; } diff --git a/src/main/java/org/simdjson/OnDemandJsonIterator.java b/src/main/java/org/simdjson/OnDemandJsonIterator.java index 5376504..3c3b2b5 100644 --- a/src/main/java/org/simdjson/OnDemandJsonIterator.java +++ b/src/main/java/org/simdjson/OnDemandJsonIterator.java @@ -4,7 +4,83 @@ import static org.simdjson.CharacterUtils.isStructuralOrWhitespace; -class OnDemandJsonIterator { +/** + * A forward-only cursor over a JSON document, returned by {@link SimdJsonParser#parseOnDemand(byte[], int)}. + *

+ * The parser runs only stage 1 (UTF-8 validation and structural indexing) and builds no tape. Values are decoded + * when the caller asks for them, in document order, and everything the caller does not ask for is skipped with + * {@link #skipChild()}. Nothing is allocated per value, except by the getters that return a boxed value. + *

+ * The root of the document must be an object or an array, entered with {@link #startIteratingRootObject()} or + * {@link #startIteratingRootArray()}. Once the root value has been read to its end, any further content in the + * document is reported as an error. + * + *

Lifecycle

+ * Each parser owns one cursor, and {@code parseOnDemand} returns that same instance every time. The cursor is valid + * until the next call to any {@code parse} or {@code parseOnDemand} method of its parser, and it must not be used + * again after it has thrown an exception. Like the parser, it is not thread-safe. + * + *

Example

+ *
{@code
+ * byte[] name = new byte[64 + OnDemandJsonIterator.STRING_BUFFER_PADDING];
+ * OnDemandJsonIterator it = parser.parseOnDemand(json, json.length);
+ * if (it.startIteratingRootObject() == IteratorResult.NOT_EMPTY) {
+ *     do {
+ *         int nameLength = it.getFieldName(name);
+ *         it.moveToFieldValue();
+ *         if (Arrays.equals(name, 0, nameLength, ID, 0, ID.length)) {
+ *             id = it.getNonNullLong();
+ *         } else {
+ *             it.skipChild();
+ *         }
+ *     } while (it.nextObjectField());
+ * }
+ * }
+ * + *

String buffers

+ * {@link #getString(byte[])} and {@link #getFieldName(byte[])} decode into a caller-supplied array. The decoder + * stores whole SIMD vectors, so it may write up to {@link #STRING_BUFFER_PADDING} bytes past the end of the decoded + * string. An array of at least {@code n + STRING_BUFFER_PADDING} bytes is always large enough for a string whose + * decoded length is at most {@code n}; the decoded length never exceeds the number of bytes between the quotes in the + * input. A smaller array may cause an {@link IndexOutOfBoundsException}. + * + *

Depth

+ * {@link #getDepth()} is the nesting level of the cursor's position. The root value is at depth 1, and the fields + * and elements of a container at depth {@code d} are at depth {@code d + 1}. Reading or skipping a value at depth + * {@code d} leaves the depth at {@code d - 1}, and so does closing a container at depth {@code d} + * ({@link #nextObjectField()} or {@link #nextArrayElement()} returning {@code false}). Entering a container differs + * between objects and arrays: + *
    + *
  • {@link #startIteratingObject()} leaves the depth at {@code d}: the cursor is at a field name, which is not a + * value. {@link #moveToFieldValue()} then moves to depth {@code d + 1}.
  • + *
  • {@link #startIteratingArray()} moves to depth {@code d + 1}: the cursor is at the first element. + * {@link #nextArrayElement()} returning {@code true} moves to depth {@code d + 1} again.
  • + *
+ * In both cases, after a field value or an element has been read the depth is {@code d} again. To skip the rest of + * a container from anywhere inside it, pass {@code d - 1} to {@link #skipChild(int)}. The simplest way to get that + * number is to read the depth just before entering the container: + *
{@code
+ * int parentDepth = it.getDepth() - 1;
+ * if (it.startIteratingObject() == IteratorResult.NOT_EMPTY) {
+ *     int nameLength = it.getFieldName(name);
+ *     it.moveToFieldValue();
+ *     if (!Arrays.equals(name, 0, nameLength, TYPE, 0, TYPE.length)) {
+ *         it.skipChild(parentDepth); // the rest of this object, including its closing brace
+ *         return;
+ *     }
+ *     ...
+ * }
+ * }
+ * Right after a successful {@code startIteratingObject()} the same number is {@code getDepth() - 1}; right after a + * successful {@code startIteratingArray()} it is {@code getDepth() - 2}. + */ +public class OnDemandJsonIterator { + + /** + * The number of bytes that {@link #getString(byte[])} and {@link #getFieldName(byte[])} may write past the end of + * the decoded string: the size of one SIMD vector of the selected species (32 or 64). + */ + public static final int STRING_BUFFER_PADDING = StringParser.MAX_BYTES_WRITTEN_PAST_STRING; private static final byte SPACE = 0x20; private static final int[] SKIP_DEPTH_PER_CHARACTER = new int[127]; @@ -40,11 +116,89 @@ void init(byte[] buffer, int len) { this.depth = 1; } - void skipChild() { + /** + * Returns the byte offset in the input of the next structural token, that is, of the first byte of the value the + * cursor is at. Called where a value is expected, it gives the start of that value, for example the offset of + * the opening brace of an object before {@link #startIteratingObject()}. The cursor does not move. + * + * @return the offset of the next token, or the length of the document if the cursor has reached its end + */ + public int peekOffset() { + if (indexer.hasNext()) { + return indexer.peek(); + } + return len; + } + + /** + * Returns the byte offset in the input of the most recently consumed structural token. Once an object or an + * array has been read to its end, or skipped, this is the offset of its closing brace or bracket, so together + * with {@link #peekOffset()} taken before the value it gives the exact span of the value: + *
{@code
+     * int start = it.peekOffset();
+     * it.skipChild();
+     * int end = it.lastTokenOffset() + 1; // exclusive
+     * }
+ * For a scalar value, this is the offset of its first byte. + * + * @return the offset of the last consumed token + * @throws IllegalStateException if no token has been consumed yet + */ + public int lastTokenOffset() { + if (indexer.isStart()) { + throw new IllegalStateException("No token has been consumed yet."); + } + return indexer.lastIndex(); + } + + /** + * Returns the JSON type of the value the cursor is at, determined from its first byte. The cursor does not move, + * and the value is not validated: a malformed literal such as {@code nul} is reported here as {@link ValueType#NULL} + * and rejected by the getter. Call it where a value is expected: after {@link #moveToFieldValue()}, after + * {@link #startIteratingArray()} returned {@link IteratorResult#NOT_EMPTY}, or after {@link #nextArrayElement()} + * returned {@code true}. + * + * @return the type of the next value + * @throws JsonParsingException if the next token cannot start a value, or if the end of the document has been + * reached + */ + public ValueType peekType() { + if (!indexer.hasNext()) { + throw new JsonParsingException("Expected a value but reached end of buffer."); + } + int idx = indexer.peek(); + return switch (buffer[idx]) { + case '{' -> ValueType.OBJECT; + case '[' -> ValueType.ARRAY; + case '"' -> ValueType.STRING; + case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' -> ValueType.NUMBER; + case 't', 'f' -> ValueType.BOOLEAN; + case 'n' -> ValueType.NULL; + default -> throw new JsonParsingException("Unrecognized value starting at " + idx + + ". Expected: object, array, string, number, 'true', 'false' or 'null'."); + }; + } + + /** + * Skips the value the cursor is at, including all of its contents. Equivalent to + * {@code skipChild(getDepth() - 1)}: when the cursor is not at a value but at a field name or between the fields + * or elements of a container, it skips the rest of that container, including its closing brace or bracket. + * + * @throws JsonParsingException if the document ends before the value does + */ + public void skipChild() { skipChild(depth - 1); } - void skipChild(int parentDepth) { + /** + * Skips tokens until the depth is {@code parentDepth} or less, and does nothing if it already is. Passing the + * depth of a container minus one skips the rest of that container from anywhere inside it; see the class + * documentation for how to obtain that number. + * + * @param parentDepth the depth to return to + * @throws JsonParsingException if the document ends before that depth is reached + */ + public void skipChild(int parentDepth) { if (depth <= parentDepth) { return; } @@ -62,6 +216,7 @@ void skipChild(int parentDepth) { default: depth--; if (depth <= parentDepth) { + assertNoMoreJsonValuesAfterRoot(); return; } } @@ -73,6 +228,7 @@ void skipChild(int parentDepth) { int delta = SKIP_DEPTH_PER_CHARACTER[character]; depth += delta; if (delta < 0 && depth <= parentDepth) { + assertNoMoreJsonValuesAfterRoot(); return; } } @@ -144,7 +300,13 @@ private boolean isNull(int idx) { && buffer[idx + 3] == 'l'; } - Boolean getNonNullBoolean() { + /** + * Reads the boolean value the cursor is at. + * + * @return the value + * @throws JsonParsingException if the value is not {@code true} or {@code false} + */ + public boolean getNonNullBoolean() { int idx = indexer.getAndAdvance(); Boolean result = switch (buffer[idx]) { case 't' -> visitTrueAtom(idx); @@ -155,7 +317,13 @@ Boolean getNonNullBoolean() { return result; } - Boolean getBoolean() { + /** + * Reads the boolean or {@code null} value the cursor is at. + * + * @return the value, or {@code null} for a JSON {@code null} + * @throws JsonParsingException if the value is not {@code true}, {@code false} or {@code null} + */ + public Boolean getBoolean() { int idx = indexer.getAndAdvance(); Boolean result = switch (buffer[idx]) { case 't' -> visitTrueAtom(idx); @@ -302,7 +470,14 @@ Integer getRootInt() { return value; } - Integer getInt() { + /** + * Reads the integer or {@code null} value the cursor is at. + * + * @return the value, or {@code null} for a JSON {@code null} + * @throws JsonParsingException if the value is not an integer literal in the range of {@code int}, or + * {@code null} + */ + public Integer getInt() { depth--; int idx = indexer.getAndAdvance(); if (buffer[idx] == 'n') { @@ -312,7 +487,13 @@ Integer getInt() { return numberParser.parseInt(buffer, len, idx); } - int getNonNullInt() { + /** + * Reads the integer value the cursor is at. + * + * @return the value + * @throws JsonParsingException if the value is not an integer literal in the range of {@code int} + */ + public int getNonNullInt() { depth--; int idx = indexer.getAndAdvance(); return numberParser.parseInt(buffer, len, idx); @@ -341,13 +522,26 @@ Long getRootLong() { return value; } - long getNonNullLong() { + /** + * Reads the integer value the cursor is at. + * + * @return the value + * @throws JsonParsingException if the value is not an integer literal in the range of {@code long} + */ + public long getNonNullLong() { depth--; int idx = indexer.getAndAdvance(); return numberParser.parseLong(buffer, len, idx); } - Long getLong() { + /** + * Reads the integer or {@code null} value the cursor is at. + * + * @return the value, or {@code null} for a JSON {@code null} + * @throws JsonParsingException if the value is not an integer literal in the range of {@code long}, or + * {@code null} + */ + public Long getLong() { depth--; int idx = indexer.getAndAdvance(); if (buffer[idx] == 'n') { @@ -411,13 +605,25 @@ private byte[] padRootNumber(int idx) { return copy; } - double getNonNullDouble() { + /** + * Reads the number the cursor is at as the nearest {@code double}. Integer literals are accepted. + * + * @return the value + * @throws JsonParsingException if the value is not a number + */ + public double getNonNullDouble() { depth--; int idx = indexer.getAndAdvance(); return numberParser.parseDouble(buffer, len, idx); } - Double getDouble() { + /** + * Reads the number the cursor is at as the nearest {@code double}, or {@code null}. Integer literals are accepted. + * + * @return the value, or {@code null} for a JSON {@code null} + * @throws JsonParsingException if the value is not a number or {@code null} + */ + public Double getDouble() { depth--; int idx = indexer.getAndAdvance(); if (buffer[idx] == 'n') { @@ -427,13 +633,25 @@ Double getDouble() { return numberParser.parseDouble(buffer, len, idx); } - float getNonNullFloat() { + /** + * Reads the number the cursor is at as the nearest {@code float}. Integer literals are accepted. + * + * @return the value + * @throws JsonParsingException if the value is not a number + */ + public float getNonNullFloat() { depth--; int idx = indexer.getAndAdvance(); return numberParser.parseFloat(buffer, len, idx); } - Float getFloat() { + /** + * Reads the number the cursor is at as the nearest {@code float}, or {@code null}. Integer literals are accepted. + * + * @return the value, or {@code null} for a JSON {@code null} + * @throws JsonParsingException if the value is not a number or {@code null} + */ + public Float getFloat() { depth--; int idx = indexer.getAndAdvance(); if (buffer[idx] == 'n') { @@ -443,6 +661,41 @@ Float getFloat() { return numberParser.parseFloat(buffer, len, idx); } + /** + * Copies the number literal the cursor is at, byte for byte, into {@code destination}, without parsing it. This + * is for callers that pass the literal on verbatim, for example into a CSV file, where parsing it and formatting + * it again would cost time and could change its text ({@code 1.50} or {@code 1e2}). Integers and decimals are + * copied alike. + *

+ * Only the first byte is checked: the literal must start with {@code -} or a digit. The rest is copied up to the + * next structural character or whitespace and is not validated; use one of the number getters when the value + * must be checked against the JSON grammar. + * + * @param destination the array the literal is copied into, starting at index 0 + * @return the length of the literal in bytes + * @throws JsonParsingException if the value does not start like a number (this includes {@code null}) + * @throws IllegalArgumentException if the literal is longer than {@code destination} + */ + public int getRawNumber(byte[] destination) { + depth--; + int start = indexer.getAndAdvance(); + byte first = buffer[start]; + if (first != '-' && (first < '0' || first > '9')) { + throw new JsonParsingException("Invalid value starting at " + start + ". Expected number."); + } + int end = start + 1; + while (end < len && !isStructuralOrWhitespace(buffer[end])) { + end++; + } + int length = end - start; + if (length > destination.length) { + throw new IllegalArgumentException("The number starting at " + start + " has " + length + + " bytes, but the destination array has only " + destination.length + "."); + } + System.arraycopy(buffer, start, destination, 0, length); + return length; + } + int getRootString(byte[] stringBuffer) { depth--; int idx = indexer.getAndAdvance(); @@ -458,7 +711,21 @@ int getRootString(byte[] stringBuffer) { return len; } - int getString(byte[] stringBuffer) { + /** + * Decodes the string value the cursor is at into {@code stringBuffer}, starting at index 0, as UTF-8 with all + * escape sequences resolved. + *

+ * The decoder may write up to {@link #STRING_BUFFER_PADDING} bytes past the decoded string, so + * {@code stringBuffer} must be at least {@code n + STRING_BUFFER_PADDING} bytes long for a string whose decoded + * length is {@code n}; see the class documentation. Bytes past the returned length are unspecified. + * + * @param stringBuffer the array to decode into + * @return the decoded length in bytes, or {@code -1} for a JSON {@code null} + * @throws JsonParsingException if the value is not a string or {@code null}, or contains an invalid escape + * sequence + * @throws IndexOutOfBoundsException if the decoder needs more room than {@code stringBuffer} has + */ + public int getString(byte[] stringBuffer) { depth--; int idx = indexer.getAndAdvance(); return switch (buffer[idx]) { @@ -519,7 +786,16 @@ Character getRootChar() { return character; } - IteratorResult startIteratingArray() { + /** + * Enters the array the cursor is at. Use {@link #startIteratingRootArray()} for the root of the document. + *

+ * On {@link IteratorResult#NOT_EMPTY} the cursor is at the first element, one level deeper. On + * {@link IteratorResult#EMPTY} and {@link IteratorResult#NULL} the value has been consumed entirely. + * + * @return whether the array is empty, {@code null}, or has elements + * @throws JsonParsingException if the value is neither an array nor {@code null} + */ + public IteratorResult startIteratingArray() { int idx = indexer.peek(); if (buffer[idx] == 'n') { visitNullAtom(idx); @@ -540,12 +816,22 @@ IteratorResult startIteratingArray() { return IteratorResult.NOT_EMPTY; } - IteratorResult startIteratingRootArray() { + /** + * Enters the array at the root of the document. Behaves like {@link #startIteratingArray()}, and in addition + * checks that the document ends with the array. + * + * @return whether the array is empty, {@code null}, or has elements + * @throws JsonParsingException if the root value is neither an array nor {@code null}, if the array is not closed + * at the end of the document, or if the document has more content after an empty + * array or {@code null} + */ + public IteratorResult startIteratingRootArray() { int idx = indexer.peek(); if (buffer[idx] == 'n') { visitRootNullAtom(idx); indexer.advance(); depth--; + assertNoMoreJsonValues(); return IteratorResult.NULL; } if (buffer[idx] != '[') { @@ -565,10 +851,18 @@ IteratorResult startIteratingRootArray() { return IteratorResult.NOT_EMPTY; } - boolean nextArrayElement() { + /** + * Moves past the element that has just been read or skipped. + * + * @return {@code true} if the cursor is now at the next element, {@code false} if the array has been closed + * @throws JsonParsingException if neither a comma nor the closing bracket follows, or if the array is the root + * value and the document has more content after it + */ + public boolean nextArrayElement() { int idx = indexer.getAndAdvance(); if (buffer[idx] == ']') { depth--; + assertNoMoreJsonValuesAfterRoot(); return false; } else if (buffer[idx] == ',') { depth++; @@ -578,7 +872,17 @@ boolean nextArrayElement() { } } - IteratorResult startIteratingObject() { + /** + * Enters the object the cursor is at. Use {@link #startIteratingRootObject()} for the root of the document. + *

+ * On {@link IteratorResult#NOT_EMPTY} the cursor is at the first field name, at the same depth (see the class + * documentation). On {@link IteratorResult#EMPTY} and {@link IteratorResult#NULL} the value has been consumed + * entirely. + * + * @return whether the object is empty, {@code null}, or has fields + * @throws JsonParsingException if the value is neither an object nor {@code null} + */ + public IteratorResult startIteratingObject() { int idx = indexer.peek(); if (buffer[idx] == 'n') { visitNullAtom(idx); @@ -598,12 +902,22 @@ IteratorResult startIteratingObject() { return IteratorResult.NOT_EMPTY; } - IteratorResult startIteratingRootObject() { + /** + * Enters the object at the root of the document. Behaves like {@link #startIteratingObject()}, and in addition + * checks that the document ends with the object. + * + * @return whether the object is empty, {@code null}, or has fields + * @throws JsonParsingException if the root value is neither an object nor {@code null}, if the object is not + * closed at the end of the document, or if the document has more content after an + * empty object or {@code null} + */ + public IteratorResult startIteratingRootObject() { int idx = indexer.peek(); if (buffer[idx] == 'n') { visitRootNullAtom(idx); indexer.advance(); depth--; + assertNoMoreJsonValues(); return IteratorResult.NULL; } if (buffer[idx] != '{') { @@ -622,11 +936,19 @@ IteratorResult startIteratingRootObject() { return IteratorResult.NOT_EMPTY; } - boolean nextObjectField() { + /** + * Moves past the field value that has just been read or skipped. + * + * @return {@code true} if the cursor is now at the next field name, {@code false} if the object has been closed + * @throws JsonParsingException if neither a comma nor the closing brace follows, or if the object is the root + * value and the document has more content after it + */ + public boolean nextObjectField() { int idx = indexer.getAndAdvance(); byte character = buffer[idx]; if (character == '}') { depth--; + assertNoMoreJsonValuesAfterRoot(); return false; } else if (character == ',') { return true; @@ -635,7 +957,12 @@ boolean nextObjectField() { } } - void moveToFieldValue() { + /** + * Moves from the field name that has just been read to the field value, one level deeper. + * + * @throws JsonParsingException if no colon follows the field name + */ + public void moveToFieldValue() { int idx = indexer.getAndAdvance(); if (buffer[idx] != ':') { throw unexpectedCharException(idx, ':'); @@ -643,7 +970,21 @@ void moveToFieldValue() { depth++; } - int getFieldName(byte[] stringBuffer) { + /** + * Decodes the field name the cursor is at into {@code stringBuffer}, starting at index 0, as UTF-8 with all escape + * sequences resolved. The depth does not change; call {@link #moveToFieldValue()} next. + *

+ * The same buffer requirement as for {@link #getString(byte[])} applies: {@code stringBuffer} must be at least + * {@code n + STRING_BUFFER_PADDING} bytes long for a field name whose decoded length is {@code n}. Bytes past the + * returned length are unspecified. + * + * @param stringBuffer the array to decode into + * @return the decoded length in bytes + * @throws JsonParsingException if the cursor is not at a field name, or the name contains an invalid escape + * sequence + * @throws IndexOutOfBoundsException if the decoder needs more room than {@code stringBuffer} has + */ + public int getFieldName(byte[] stringBuffer) { int idx = indexer.getAndAdvance(); if (buffer[idx] != '"') { throw unexpectedCharException(idx, '"'); @@ -651,7 +992,13 @@ int getFieldName(byte[] stringBuffer) { return stringParser.parseString(buffer, idx, stringBuffer); } - int getDepth() { + /** + * Returns the nesting level of the cursor's position: 1 for the root value. See the class documentation for how + * each method changes it, and for how to use it with {@link #skipChild(int)}. + * + * @return the current depth + */ + public int getDepth() { return depth; } @@ -669,7 +1016,58 @@ void assertNoMoreJsonValues() { } } - enum IteratorResult { - EMPTY, NULL, NOT_EMPTY + // The root value has been read to its end exactly when the depth drops to 0. + private void assertNoMoreJsonValuesAfterRoot() { + if (depth == 0) { + assertNoMoreJsonValues(); + } + } + + /** + * The outcome of entering an object or an array. + */ + public enum IteratorResult { + /** + * The container has no fields or elements; it has been consumed. + */ + EMPTY, + /** + * The value is {@code null}; it has been consumed. + */ + NULL, + /** + * The container has at least one field or element, and the cursor is at the first one. + */ + NOT_EMPTY + } + + /** + * The JSON type of a value, as returned by {@link #peekType()}. + */ + public enum ValueType { + /** + * An object: the value starts with {. + */ + OBJECT, + /** + * An array: the value starts with {@code [}. + */ + ARRAY, + /** + * A string: the value starts with {@code "}. + */ + STRING, + /** + * A number: the value starts with {@code -} or a digit. + */ + NUMBER, + /** + * {@code true} or {@code false}. + */ + BOOLEAN, + /** + * {@code null}. + */ + NULL } } diff --git a/src/main/java/org/simdjson/SimdJsonParser.java b/src/main/java/org/simdjson/SimdJsonParser.java index 707124c..02853e2 100644 --- a/src/main/java/org/simdjson/SimdJsonParser.java +++ b/src/main/java/org/simdjson/SimdJsonParser.java @@ -10,6 +10,7 @@ public class SimdJsonParser { private final BitIndexes bitIndexes; private final JsonIterator jsonIterator; private final SchemaBasedJsonIterator schemaBasedJsonIterator; + private final OnDemandJsonIterator onDemandJsonIterator; private final byte[] paddedBuffer; public SimdJsonParser() { @@ -21,10 +22,35 @@ public SimdJsonParser(int capacity, int maxDepth) { byte[] stringBuffer = new byte[capacity]; jsonIterator = new JsonIterator(bitIndexes, stringBuffer, capacity, maxDepth, PADDING); schemaBasedJsonIterator = new SchemaBasedJsonIterator(bitIndexes, stringBuffer, PADDING); + onDemandJsonIterator = new OnDemandJsonIterator(bitIndexes, PADDING); paddedBuffer = new byte[capacity]; indexer = new StructuralIndexer(bitIndexes); } + /** + * Prepares on-demand parsing of the first {@code len} bytes of {@code buffer}: validates the input as UTF-8, + * indexes its structural characters, and returns a forward-only cursor that decodes values only when asked. No + * tape is built. See {@link OnDemandJsonIterator} for how to use the cursor. + *

+ * The parser returns the same cursor instance on every call. It is valid until the next call to any parse method + * of this parser. + * + * @param buffer the document; if fewer than 64 bytes follow {@code len}, the document is copied into an internal + * buffer, otherwise the cursor reads {@code buffer} directly, which must then not change while the + * cursor is in use + * @param len the length of the document in bytes + * @return the cursor, positioned before the root value + * @throws JsonParsingException if the input is not valid UTF-8, contains no structural element, or has an + * unclosed string or unescaped control characters in a string + */ + public OnDemandJsonIterator parseOnDemand(byte[] buffer, int len) { + byte[] padded = padIfNeeded(buffer, len); + reset(); + stage1(padded, len); + onDemandJsonIterator.init(padded, len); + return onDemandJsonIterator; + } + public T parse(byte[] buffer, int len, Class expectedType) { byte[] padded = padIfNeeded(buffer, len); reset(); diff --git a/src/main/java/org/simdjson/StringParser.java b/src/main/java/org/simdjson/StringParser.java index 6452de9..5c50f29 100644 --- a/src/main/java/org/simdjson/StringParser.java +++ b/src/main/java/org/simdjson/StringParser.java @@ -10,6 +10,9 @@ class StringParser { private static final byte BACKSLASH = '\\'; private static final byte QUOTE = '"'; private static final int BYTES_PROCESSED = VectorUtils.BYTE_SPECIES.vectorByteSize(); + // Every iteration of doParseString stores a whole vector at the current destination index, and the final + // iteration stores it at most at the end of the decoded string, so up to one vector lands past the string. + static final int MAX_BYTES_WRITTEN_PAST_STRING = BYTES_PROCESSED; private static final int MIN_HIGH_SURROGATE = 0xD800; private static final int MAX_HIGH_SURROGATE = 0xDBFF; private static final int MIN_LOW_SURROGATE = 0xDC00; diff --git a/src/test/java/org/simdjson/OnDemandParsingTest.java b/src/test/java/org/simdjson/OnDemandParsingTest.java new file mode 100644 index 0000000..08972dd --- /dev/null +++ b/src/test/java/org/simdjson/OnDemandParsingTest.java @@ -0,0 +1,1152 @@ +package org.simdjson; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.simdjson.OnDemandJsonIterator.IteratorResult; +import org.simdjson.OnDemandJsonIterator.ValueType; + +import java.util.ArrayList; +import java.util.List; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.simdjson.OnDemandJsonIterator.STRING_BUFFER_PADDING; +import static org.simdjson.testutils.TestUtils.toUtf8; + +public class OnDemandParsingTest { + + private final byte[] stringBuffer = new byte[256 + STRING_BUFFER_PADDING]; + + @Test + public void rootObject() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": 1, \"b\": \"x\", \"c\": true}"); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(fieldName(it)).isEqualTo("a"); + it.moveToFieldValue(); + assertThat(it.getNonNullLong()).isEqualTo(1); + assertThat(it.nextObjectField()).isTrue(); + assertThat(fieldName(it)).isEqualTo("b"); + it.moveToFieldValue(); + assertThat(string(it)).isEqualTo("x"); + assertThat(it.nextObjectField()).isTrue(); + assertThat(fieldName(it)).isEqualTo("c"); + it.moveToFieldValue(); + assertThat(it.getNonNullBoolean()).isTrue(); + assertThat(it.nextObjectField()).isFalse(); + assertThat(it.getDepth()).isEqualTo(0); + } + + @Test + public void rootArray() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[1, 2, 3]"); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + List values = new ArrayList<>(); + do { + values.add(it.getNonNullLong()); + } while (it.nextArrayElement()); + assertThat(values).containsExactly(1L, 2L, 3L); + assertThat(it.getDepth()).isEqualTo(0); + } + + @Test + public void nestedObjectsAndArrays() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": {\"b\": [1, {\"c\": [true, null]}]}, \"d\": [[2], [3, 4]]}"); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(fieldName(it)).isEqualTo("a"); + it.moveToFieldValue(); + assertThat(it.startIteratingObject()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(fieldName(it)).isEqualTo("b"); + it.moveToFieldValue(); + assertThat(it.startIteratingArray()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(it.getNonNullLong()).isEqualTo(1); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.startIteratingObject()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(fieldName(it)).isEqualTo("c"); + it.moveToFieldValue(); + assertThat(it.startIteratingArray()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(it.getBoolean()).isTrue(); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getBoolean()).isNull(); + assertThat(it.nextArrayElement()).isFalse(); + assertThat(it.nextObjectField()).isFalse(); + assertThat(it.nextArrayElement()).isFalse(); + assertThat(it.nextObjectField()).isFalse(); + assertThat(it.nextObjectField()).isTrue(); + assertThat(fieldName(it)).isEqualTo("d"); + it.moveToFieldValue(); + assertThat(it.startIteratingArray()).isEqualTo(IteratorResult.NOT_EMPTY); + List> rows = new ArrayList<>(); + do { + assertThat(it.startIteratingArray()).isEqualTo(IteratorResult.NOT_EMPTY); + List row = new ArrayList<>(); + do { + row.add(it.getNonNullLong()); + } while (it.nextArrayElement()); + rows.add(row); + } while (it.nextArrayElement()); + assertThat(rows).containsExactly(List.of(2L), List.of(3L, 4L)); + assertThat(it.nextObjectField()).isFalse(); + assertThat(it.getDepth()).isEqualTo(0); + } + + @ParameterizedTest + @ValueSource(strings = {"{}", "{ }", " {}"}) + public void emptyRootObject(String jsonStr) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8(jsonStr); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.EMPTY); + assertThat(it.getDepth()).isEqualTo(0); + } + + @ParameterizedTest + @ValueSource(strings = {"[]", "[ ]", " []"}) + public void emptyRootArray(String jsonStr) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8(jsonStr); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.EMPTY); + assertThat(it.getDepth()).isEqualTo(0); + } + + @Test + public void nullAtRoot() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("null"); + + // when + IteratorResult objectResult = parser.parseOnDemand(json, json.length).startIteratingRootObject(); + IteratorResult arrayResult = parser.parseOnDemand(json, json.length).startIteratingRootArray(); + + // then + assertThat(objectResult).isEqualTo(IteratorResult.NULL); + assertThat(arrayResult).isEqualTo(IteratorResult.NULL); + } + + @Test + public void emptyAndNullNestedContainers() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": {}, \"b\": [], \"c\": null, \"d\": null, \"e\": 5}"); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getFieldName(stringBuffer); + it.moveToFieldValue(); + assertThat(it.startIteratingObject()).isEqualTo(IteratorResult.EMPTY); + assertThat(it.getDepth()).isEqualTo(1); + assertThat(it.nextObjectField()).isTrue(); + it.getFieldName(stringBuffer); + it.moveToFieldValue(); + assertThat(it.startIteratingArray()).isEqualTo(IteratorResult.EMPTY); + assertThat(it.getDepth()).isEqualTo(1); + assertThat(it.nextObjectField()).isTrue(); + it.getFieldName(stringBuffer); + it.moveToFieldValue(); + assertThat(it.startIteratingObject()).isEqualTo(IteratorResult.NULL); + assertThat(it.getDepth()).isEqualTo(1); + assertThat(it.nextObjectField()).isTrue(); + it.getFieldName(stringBuffer); + it.moveToFieldValue(); + assertThat(it.startIteratingArray()).isEqualTo(IteratorResult.NULL); + assertThat(it.getDepth()).isEqualTo(1); + assertThat(it.nextObjectField()).isTrue(); + assertThat(fieldName(it)).isEqualTo("e"); + it.moveToFieldValue(); + assertThat(it.getNonNullInt()).isEqualTo(5); + assertThat(it.nextObjectField()).isFalse(); + } + + @Test + public void numbersAndBooleans() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[-9223372036854775808, 9223372036854775807, null, -2147483648, 2147483647, null, " + + "1.5, 7, -2.5e-3, null, 0.25, 3, null, true, false, true, null]"); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(it.getNonNullLong()).isEqualTo(Long.MIN_VALUE); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getLong()).isEqualTo(Long.MAX_VALUE); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getLong()).isNull(); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getNonNullInt()).isEqualTo(Integer.MIN_VALUE); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getInt()).isEqualTo(Integer.MAX_VALUE); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getInt()).isNull(); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getNonNullDouble()).isEqualTo(1.5); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getNonNullDouble()).isEqualTo(7.0); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getDouble()).isEqualTo(-2.5e-3); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getDouble()).isNull(); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getNonNullFloat()).isEqualTo(0.25f); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getFloat()).isEqualTo(3.0f); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getFloat()).isNull(); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getNonNullBoolean()).isTrue(); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getNonNullBoolean()).isFalse(); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getBoolean()).isTrue(); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getBoolean()).isNull(); + assertThat(it.nextArrayElement()).isFalse(); + } + + @Test + public void stringsAndNull() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[\"\", \"abc\", null]"); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(it.getString(stringBuffer)).isEqualTo(0); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(string(it)).isEqualTo("abc"); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getString(stringBuffer)).isEqualTo(-1); + assertThat(it.nextArrayElement()).isFalse(); + } + + @ParameterizedTest + @CsvSource({ + "\\u0105\\u0107\\u015B, \u0105\u0107\u015B", + "\\u03B1\\u03B2\\u03B3, \u03B1\u03B2\u03B3", + "\\uD83D\\uDE00abc\\uD83D\\uDE00, \uD83D\uDE00abc\uD83D\uDE00", + "\u0105\u20AC\uD83D\uDE00, \u0105\u20AC\uD83D\uDE00", + "a\\\"b\\\\c\\/d, a\"b\\c/d" + }) + public void escapedAndNonAsciiStringsAndFieldNames(String jsonStr, String expected) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"" + jsonStr + "\": \"" + jsonStr + "\"}"); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(fieldName(it)).isEqualTo(expected); + it.moveToFieldValue(); + assertThat(string(it)).isEqualTo(expected); + assertThat(it.nextObjectField()).isFalse(); + } + + @Test + public void controlCharacterEscapesInStringsAndFieldNames() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"\\b\\f\\n\\r\\t\": \"\\t\\r\\n\\f\\b\\u0000\"}"); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(fieldName(it)).isEqualTo("\b\f\n\r\t"); + it.moveToFieldValue(); + assertThat(string(it)).isEqualTo("\t\r\n\f\b\u0000"); + assertThat(it.nextObjectField()).isFalse(); + } + + @Test + public void skipChildOnEveryKindOfValue() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"s\": \"x:y\", \"n\": -1.5e3, \"t\": true, \"f\": false, \"z\": null, " + + "\"o\": {\"a\": [1, {\"b\": \"}\"}], \"c\": {}}, \"e\": {}, \"a\": [[1], {\"c\": [3]}, []], " + + "\"last\": 7}"); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + List skipped = new ArrayList<>(); + long last = 0; + do { + String name = fieldName(it); + it.moveToFieldValue(); + if (name.equals("last")) { + last = it.getNonNullLong(); + } else { + it.skipChild(); + assertThat(it.getDepth()).isEqualTo(1); + skipped.add(name); + } + } while (it.nextObjectField()); + assertThat(skipped).containsExactly("s", "n", "t", "f", "z", "o", "e", "a"); + assertThat(last).isEqualTo(7); + } + + @Test + public void skipChildOnArrayElements() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[\"x\", 1, {\"a\": [2]}, [3, [4]], null, true, 5]"); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + int skipped = 0; + for (int i = 0; i < 6; i++) { + it.skipChild(); + assertThat(it.getDepth()).isEqualTo(1); + assertThat(it.nextArrayElement()).isTrue(); + skipped++; + } + assertThat(skipped).isEqualTo(6); + assertThat(it.getNonNullLong()).isEqualTo(5); + assertThat(it.nextArrayElement()).isFalse(); + } + + @Test + public void depthOfObjects() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": {\"x\": 1, \"y\": {\"z\": [1, 2]}, \"w\": 3}, \"b\": 2}"); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.getDepth()).isEqualTo(1); + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(it.getDepth()).isEqualTo(1); + assertThat(fieldName(it)).isEqualTo("a"); + assertThat(it.getDepth()).isEqualTo(1); + it.moveToFieldValue(); + assertThat(it.getDepth()).isEqualTo(2); + int parentDepth = it.getDepth() - 1; + assertThat(it.startIteratingObject()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(it.getDepth()).isEqualTo(2); + assertThat(it.getDepth() - 1).isEqualTo(parentDepth); + assertThat(fieldName(it)).isEqualTo("x"); + it.moveToFieldValue(); + assertThat(it.getDepth()).isEqualTo(3); + assertThat(it.getNonNullLong()).isEqualTo(1); + assertThat(it.getDepth()).isEqualTo(2); + assertThat(it.nextObjectField()).isTrue(); + assertThat(it.getDepth()).isEqualTo(2); + assertThat(fieldName(it)).isEqualTo("y"); + it.moveToFieldValue(); + assertThat(it.startIteratingObject()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(fieldName(it)).isEqualTo("z"); + it.moveToFieldValue(); + assertThat(it.startIteratingArray()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(it.getDepth()).isEqualTo(5); + + // when: skipping the rest of "a" from two levels below it + it.skipChild(parentDepth); + + // then + assertThat(it.getDepth()).isEqualTo(parentDepth); + assertThat(it.nextObjectField()).isTrue(); + assertThat(fieldName(it)).isEqualTo("b"); + it.moveToFieldValue(); + assertThat(it.getNonNullLong()).isEqualTo(2); + assertThat(it.nextObjectField()).isFalse(); + assertThat(it.getDepth()).isEqualTo(0); + } + + @Test + public void depthOfArrays() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": [1, [2, [3, 4], 5], 6], \"b\": 2}"); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(fieldName(it)).isEqualTo("a"); + it.moveToFieldValue(); + assertThat(it.getDepth()).isEqualTo(2); + int parentDepth = it.getDepth() - 1; + assertThat(it.startIteratingArray()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(it.getDepth()).isEqualTo(3); + assertThat(it.getDepth() - 2).isEqualTo(parentDepth); + assertThat(it.getNonNullLong()).isEqualTo(1); + assertThat(it.getDepth()).isEqualTo(2); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getDepth()).isEqualTo(3); + assertThat(it.startIteratingArray()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(it.getDepth()).isEqualTo(4); + assertThat(it.getNonNullLong()).isEqualTo(2); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.startIteratingArray()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(it.getNonNullLong()).isEqualTo(3); + assertThat(it.getDepth()).isEqualTo(4); + + // when: skipping the rest of "a" from two levels below it + it.skipChild(parentDepth); + + // then + assertThat(it.getDepth()).isEqualTo(parentDepth); + assertThat(it.nextObjectField()).isTrue(); + assertThat(fieldName(it)).isEqualTo("b"); + it.moveToFieldValue(); + assertThat(it.getNonNullLong()).isEqualTo(2); + assertThat(it.nextObjectField()).isFalse(); + } + + @Test + public void skipRestOfObjectBetweenFields() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[{\"a\": 1, \"b\": {\"c\": 2}, \"d\": [3]}, 4]"); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(it.startIteratingObject()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(fieldName(it)).isEqualTo("a"); + it.moveToFieldValue(); + assertThat(it.getNonNullLong()).isEqualTo(1); + it.skipChild(); + assertThat(it.getDepth()).isEqualTo(1); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getNonNullLong()).isEqualTo(4); + assertThat(it.nextArrayElement()).isFalse(); + } + + @Test + public void skipRestOfObjectAtFieldName() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[{\"a\": 1, \"b\": {\"c\": 2}}, 4]"); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(it.startIteratingObject()).isEqualTo(IteratorResult.NOT_EMPTY); + it.skipChild(); + assertThat(it.getDepth()).isEqualTo(1); + assertThat(it.nextArrayElement()).isTrue(); + assertThat(it.getNonNullLong()).isEqualTo(4); + assertThat(it.nextArrayElement()).isFalse(); + } + + @Test + public void skipRestOfArrayBetweenElements() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": [1, [2], {\"b\": 3}], \"c\": 4}"); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getFieldName(stringBuffer); + it.moveToFieldValue(); + assertThat(it.startIteratingArray()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(it.getNonNullLong()).isEqualTo(1); + it.skipChild(); + assertThat(it.getDepth()).isEqualTo(1); + assertThat(it.nextObjectField()).isTrue(); + assertThat(fieldName(it)).isEqualTo("c"); + it.moveToFieldValue(); + assertThat(it.getNonNullLong()).isEqualTo(4); + assertThat(it.nextObjectField()).isFalse(); + } + + @Test + public void skipChildWithDepthAlreadyReachedDoesNothing() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": 1, \"b\": 2}"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getFieldName(stringBuffer); + it.moveToFieldValue(); + it.getNonNullLong(); + int offset = it.peekOffset(); + + // when + it.skipChild(1); + + // then + assertThat(it.getDepth()).isEqualTo(1); + assertThat(it.peekOffset()).isEqualTo(offset); + } + + @ParameterizedTest + @CsvSource({ + "'{\"a\": 1}', OBJECT", + "{}, OBJECT", + "'[1, 2]', ARRAY", + "[], ARRAY", + "\"abc\", STRING", + "\"\", STRING", + "0, NUMBER", + "-1, NUMBER", + "1.5e3, NUMBER", + "true, BOOLEAN", + "false, BOOLEAN", + "null, NULL" + }) + public void peekType(String value, ValueType expected) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"v\": " + value + "}"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getFieldName(stringBuffer); + it.moveToFieldValue(); + int offset = it.peekOffset(); + + // when + ValueType type = it.peekType(); + + // then + assertThat(type).isEqualTo(expected); + assertThat(it.peekOffset()).isEqualTo(offset); + assertThat(it.getDepth()).isEqualTo(2); + it.skipChild(); + assertThat(it.nextObjectField()).isFalse(); + } + + @Test + public void peekTypeOfArrayElements() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[{}, [], \"a\", 1, true, null]"); + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // then + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + List types = new ArrayList<>(); + do { + types.add(it.peekType()); + it.skipChild(); + } while (it.nextArrayElement()); + assertThat(types).containsExactly( + ValueType.OBJECT, ValueType.ARRAY, ValueType.STRING, ValueType.NUMBER, ValueType.BOOLEAN, ValueType.NULL + ); + } + + @Test + public void peekTypeOfUnrecognizedValue() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[x]"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, it::peekType); + + // then + assertThat(ex) + .hasMessage("Unrecognized value starting at 1. Expected: object, array, string, number, 'true', 'false' or 'null'."); + } + + @Test + public void peekTypeAtEndOfDocument() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[1]"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getNonNullLong(); + assertThat(it.nextArrayElement()).isFalse(); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, it::peekType); + + // then + assertThat(ex).hasMessage("Expected a value but reached end of buffer."); + } + + @ParameterizedTest + @ValueSource(strings = {"{\"b\": [1, {\"c\": \"]}\"}], \"d\": {}}", "[[1, 2], {\"e\": null}, []]", "{}", "[]"}) + public void byteSpanOfSkippedValue(String value) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": " + value + " , \"z\": 1}"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getFieldName(stringBuffer); + it.moveToFieldValue(); + + // when + int start = it.peekOffset(); + it.skipChild(); + int end = it.lastTokenOffset() + 1; + + // then + assertThat(new String(json, start, end - start, UTF_8)).isEqualTo(value); + } + + @Test + public void byteSpanOfIteratedValues() { + // given + SimdJsonParser parser = new SimdJsonParser(); + String object = "{\"b\": [1, 2]}"; + String array = "[3, {\"c\": 4}]"; + byte[] json = toUtf8("[ " + object + ", " + array + " ]"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + + // when + int objectStart = it.peekOffset(); + assertThat(it.startIteratingObject()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getFieldName(stringBuffer); + it.moveToFieldValue(); + it.skipChild(); + assertThat(it.nextObjectField()).isFalse(); + int objectEnd = it.lastTokenOffset() + 1; + assertThat(it.nextArrayElement()).isTrue(); + int arrayStart = it.peekOffset(); + assertThat(it.startIteratingArray()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getNonNullLong(); + assertThat(it.nextArrayElement()).isTrue(); + it.skipChild(); + assertThat(it.nextArrayElement()).isFalse(); + int arrayEnd = it.lastTokenOffset() + 1; + + // then + assertThat(new String(json, objectStart, objectEnd - objectStart, UTF_8)).isEqualTo(object); + assertThat(new String(json, arrayStart, arrayEnd - arrayStart, UTF_8)).isEqualTo(array); + } + + @Test + public void offsetsOfScalars() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[ \"ab\" , 12 ]"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // when + int rootOffset = it.peekOffset(); + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + int rootLastToken = it.lastTokenOffset(); + int stringOffset = it.peekOffset(); + it.getString(stringBuffer); + int stringLastToken = it.lastTokenOffset(); + assertThat(it.nextArrayElement()).isTrue(); + int numberOffset = it.peekOffset(); + it.getNonNullLong(); + int numberLastToken = it.lastTokenOffset(); + + // then + assertThat(rootOffset).isEqualTo(0); + assertThat(rootLastToken).isEqualTo(0); + assertThat(stringOffset).isEqualTo(2); + assertThat(stringLastToken).isEqualTo(2); + assertThat(numberOffset).isEqualTo(10); + assertThat(numberLastToken).isEqualTo(10); + } + + @Test + public void peekOffsetAtEndOfDocument() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": 1} "); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + + // when + it.skipChild(); + + // then + assertThat(it.getDepth()).isEqualTo(0); + assertThat(it.peekOffset()).isEqualTo(json.length); + assertThat(it.lastTokenOffset()).isEqualTo(7); + } + + @Test + public void lastTokenOffsetBeforeAnyTokenWasConsumed() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": 1}"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // when + IllegalStateException ex = assertThrows(IllegalStateException.class, it::lastTokenOffset); + + // then + assertThat(ex).hasMessage("No token has been consumed yet."); + } + + @ParameterizedTest + @ValueSource(strings = { + "0", "-0", "7", "-12", "9223372036854775807", "123456789012345678901234567890", + "3.14", "-0.5", "1.50", "0.000001", + "1e10", "1E10", "1.5e-3", "-2E+5", "6.02214076e23" + }) + public void rawNumber(String literal) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": " + literal + ", \"b\": [" + literal + "]}"); + byte[] destination = new byte[literal.length()]; + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getFieldName(stringBuffer); + it.moveToFieldValue(); + + // when + int fieldLength = it.getRawNumber(destination); + String fieldLiteral = new String(destination, 0, fieldLength, UTF_8); + assertThat(it.nextObjectField()).isTrue(); + it.getFieldName(stringBuffer); + it.moveToFieldValue(); + assertThat(it.startIteratingArray()).isEqualTo(IteratorResult.NOT_EMPTY); + int elementLength = it.getRawNumber(destination); + String elementLiteral = new String(destination, 0, elementLength, UTF_8); + + // then + assertThat(fieldLiteral).isEqualTo(literal); + assertThat(elementLiteral).isEqualTo(literal); + assertThat(it.nextArrayElement()).isFalse(); + assertThat(it.nextObjectField()).isFalse(); + } + + @ParameterizedTest + @ValueSource(strings = {"\"1\"", "null", "true", "false", "{}", "[]"}) + public void rawNumberOfNonNumber(String value) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[" + value + "]"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, () -> it.getRawNumber(new byte[16])); + + // then + assertThat(ex).hasMessage("Invalid value starting at 1. Expected number."); + } + + @Test + public void rawNumberIntoTooSmallDestination() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[12.345]"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + + // when + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> it.getRawNumber(new byte[5])); + + // then + assertThat(ex).hasMessage("The number starting at 1 has 6 bytes, but the destination array has only 5."); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "1 | getString | Invalid value starting at 1. Expected either string or 'null'.", + "true | getString | Invalid value starting at 1. Expected either string or 'null'.", + "1 | getNonNullBoolean | Unrecognized boolean value. Expected: 'true' or 'false'.", + "\"a\" | getNonNullLong | Invalid number. Minus has to be followed by a digit.", + "1.5 | getNonNullLong | Number has to be followed by a structural character or whitespace.", + "\"a\" | getNonNullDouble | Invalid number. Minus has to be followed by a digit.", + "[] | startIteratingObject | Expected '{' but got: '['.", + "{} | startIteratingArray | Expected '[' but got: '{'." + }) + public void wrongTypeAccess(String value, String accessor, String expectedMessage) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[" + value + "]"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, () -> { + switch (accessor) { + case "getString" -> it.getString(stringBuffer); + case "getNonNullBoolean" -> it.getNonNullBoolean(); + case "getNonNullLong" -> it.getNonNullLong(); + case "getNonNullDouble" -> it.getNonNullDouble(); + case "startIteratingObject" -> it.startIteratingObject(); + case "startIteratingArray" -> it.startIteratingArray(); + default -> throw new IllegalArgumentException(accessor); + } + }); + + // then + assertThat(ex).hasMessage(expectedMessage); + } + + @Test + public void fieldNameWhereValueIsExpected() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[1]"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, () -> it.getFieldName(stringBuffer)); + + // then + assertThat(ex).hasMessage("Expected '\"' but got: '1'."); + } + + @ParameterizedTest + @ValueSource(strings = {"{\"a\": 1", "{\"a\": 1 2", "{\"a\": 1] "}) + public void unclosedRootObject(String jsonStr) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8(jsonStr); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, it::startIteratingRootObject); + + // then + assertThat(ex).hasMessage("Unclosed object. Missing '}' for starting '{'."); + } + + @ParameterizedTest + @ValueSource(strings = {"[1, 2", "[1, 2 3", "[1, 2} "}) + public void unclosedRootArray(String jsonStr) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8(jsonStr); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, it::startIteratingRootArray); + + // then + assertThat(ex).hasMessage("Unclosed array. Missing ']' for starting '['."); + } + + @Test + public void unclosedNestedObject() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": {\"b\": 1}"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getFieldName(stringBuffer); + it.moveToFieldValue(); + assertThat(it.startIteratingObject()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getFieldName(stringBuffer); + it.moveToFieldValue(); + it.getNonNullLong(); + assertThat(it.nextObjectField()).isFalse(); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, it::nextObjectField); + + // then + assertThat(ex).hasMessage("Expected ',' but reached end of buffer."); + } + + @Test + public void unclosedNestedObjectWhileSkipping() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[[{\"a\": [1]]"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, it::skipChild); + + // then + assertThat(ex).hasMessage("Not enough close braces."); + } + + @Test + public void missingColon() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\" 1}"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getFieldName(stringBuffer); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, it::moveToFieldValue); + + // then + assertThat(ex).hasMessage("Expected ':' but got: '1'."); + } + + @Test + public void missingCommaBetweenFields() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": 1 \"b\": 2}"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getFieldName(stringBuffer); + it.moveToFieldValue(); + it.getNonNullLong(); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, it::nextObjectField); + + // then + assertThat(ex).hasMessage("Expected ',' but got: '\"'."); + } + + @Test + public void missingCommaBetweenElements() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[1 2]"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getNonNullLong(); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, it::nextArrayElement); + + // then + assertThat(ex).hasMessage("Missing comma between array values"); + } + + @Test + public void trailingContentAfterRootObject() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": 1}{\"b\": 2}"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getFieldName(stringBuffer); + it.moveToFieldValue(); + it.getNonNullLong(); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, it::nextObjectField); + + // then + assertThat(ex).hasMessage("More than one JSON value at the root of the document, or extra characters at the end of the JSON!"); + } + + @Test + public void trailingContentAfterRootArray() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[1] [2]"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getNonNullLong(); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, it::nextArrayElement); + + // then + assertThat(ex).hasMessage("More than one JSON value at the root of the document, or extra characters at the end of the JSON!"); + } + + @Test + public void trailingContentAfterSkippedRootObject() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": 1} \"b\" }"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, it::skipChild); + + // then + assertThat(ex).hasMessage("More than one JSON value at the root of the document, or extra characters at the end of the JSON!"); + } + + @ParameterizedTest + @ValueSource(strings = {"{} {}", "null {}"}) + public void trailingContentAfterEmptyOrNullRootObject(String jsonStr) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8(jsonStr); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, it::startIteratingRootObject); + + // then + assertThat(ex).hasMessage("More than one JSON value at the root of the document, or extra characters at the end of the JSON!"); + } + + @ParameterizedTest + @ValueSource(strings = {"", " ", "\n\t "}) + public void noStructuralElement(String jsonStr) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8(jsonStr); + + // when + JsonParsingException ex = assertThrows(JsonParsingException.class, () -> parser.parseOnDemand(json, json.length)); + + // then + assertThat(ex).hasMessage("No structural element found."); + } + + @Test + public void stringBufferPaddingIsOneVector() { + // expect + assertThat(STRING_BUFFER_PADDING).isEqualTo(VectorUtils.BYTE_SPECIES.vectorByteSize()); + } + + @Test + public void stringBufferWithPaddingIsLargeEnough() { + // given + SimdJsonParser parser = new SimdJsonParser(); + for (int length = 0; length <= 3 * STRING_BUFFER_PADDING; length++) { + String plain = "a".repeat(length); + String escaped = "\\n".repeat(length); + byte[] json = toUtf8("{\"" + plain + "\": \"" + escaped + "\"}"); + byte[] destination = new byte[length + STRING_BUFFER_PADDING]; + + // when + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + int nameLength = it.getFieldName(destination); + String name = new String(destination, 0, nameLength, UTF_8); + it.moveToFieldValue(); + int valueLength = it.getString(destination); + String value = new String(destination, 0, valueLength, UTF_8); + + // then + assertThat(name).isEqualTo(plain); + assertThat(value).isEqualTo("\n".repeat(length)); + assertThat(it.nextObjectField()).isFalse(); + } + } + + @ParameterizedTest + @ValueSource(ints = {0, 1, 2}) + public void stringBufferWithoutPaddingIsTooSmall(int vectors) { + // given + SimdJsonParser parser = new SimdJsonParser(); + int length = vectors * STRING_BUFFER_PADDING; + byte[] json = toUtf8("{\"" + "k".repeat(length) + "\": \"" + "v".repeat(length) + "\"}"); + byte[] destination = new byte[length + STRING_BUFFER_PADDING - 1]; + OnDemandJsonIterator nameIt = parser.parseOnDemand(json, json.length); + assertThat(nameIt.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + + // when + assertThrows(IndexOutOfBoundsException.class, () -> nameIt.getFieldName(destination)); + OnDemandJsonIterator valueIt = parser.parseOnDemand(json, json.length); + assertThat(valueIt.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + valueIt.getFieldName(new byte[length + STRING_BUFFER_PADDING]); + valueIt.moveToFieldValue(); + + // then + assertThrows(IndexOutOfBoundsException.class, () -> valueIt.getString(destination)); + } + + @Test + public void parserReuse() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] first = toUtf8("{\"a\": 123456789, \"b\": \"long string value\"}"); + byte[] second = toUtf8("[7]"); + + // when + OnDemandJsonIterator firstIt = parser.parseOnDemand(first, first.length); + assertThat(firstIt.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(fieldName(firstIt)).isEqualTo("a"); + firstIt.moveToFieldValue(); + assertThat(firstIt.getNonNullLong()).isEqualTo(123456789); + OnDemandJsonIterator secondIt = parser.parseOnDemand(second, second.length); + + // then + assertThat(secondIt).isSameAs(firstIt); + assertThat(secondIt.getDepth()).isEqualTo(1); + assertThat(secondIt.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + assertThat(secondIt.getNonNullLong()).isEqualTo(7); + assertThat(secondIt.nextArrayElement()).isFalse(); + assertThat(secondIt.peekOffset()).isEqualTo(second.length); + } + + @Test + public void parserReuseAcrossEntryPoints() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": [1, 2]}"); + + // when + JsonValue dom = parser.parse(json, json.length); + long domFirst = dom.get("a").arrayIterator().next().asLong(); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getFieldName(stringBuffer); + it.moveToFieldValue(); + assertThat(it.startIteratingArray()).isEqualTo(IteratorResult.NOT_EMPTY); + long onDemandFirst = it.getNonNullLong(); + + // then + assertThat(onDemandFirst).isEqualTo(domFirst); + } + + private String fieldName(OnDemandJsonIterator it) { + int length = it.getFieldName(stringBuffer); + return new String(stringBuffer, 0, length, UTF_8); + } + + private String string(OnDemandJsonIterator it) { + int length = it.getString(stringBuffer); + return new String(stringBuffer, 0, length, UTF_8); + } +} From 60066a26fe0723230e77a1354997e0fd38fa9d73 Mon Sep 17 00:00:00 2001 From: Morris Meyer Date: Sat, 21 Nov 2026 20:40:08 +0000 Subject: [PATCH 5/9] Add allocation-free, index-based navigation to JsonValue Extracting a few fields from many values of a large document with get(String) and the iterators allocates a JsonValue per value, an iterator per array and a byte[] per key. JsonValue gains: - get(byte[]), get(String) with a pre-encoded name - index(), field, firstElement, advance and scopeEnd, which navigate the tape of the whole document with int indices - is{Object,Array,String,Long,Double,Boolean,Null}At type tests - stringAt, longAt, doubleAt, numberAt and booleanAt getters - stringBytes, byteOffset, byteLength and stringEquals, which read decoded strings straight from the parser's string buffer Methods that need a value of a particular type throw an IllegalArgumentException for an index of another type, so a wrong index cannot read unrelated tape entries. --- src/main/java/org/simdjson/JsonValue.java | 344 +++++++++++++++++- .../org/simdjson/JsonValueNavigationTest.java | 303 +++++++++++++++ 2 files changed, 645 insertions(+), 2 deletions(-) create mode 100644 src/test/java/org/simdjson/JsonValueNavigationTest.java diff --git a/src/main/java/org/simdjson/JsonValue.java b/src/main/java/org/simdjson/JsonValue.java index 6877519..688b002 100644 --- a/src/main/java/org/simdjson/JsonValue.java +++ b/src/main/java/org/simdjson/JsonValue.java @@ -89,7 +89,17 @@ private String getString(int tapeIdx) { } public JsonValue get(String name) { - byte[] bytes = name.getBytes(UTF_8); + return get(name.getBytes(UTF_8)); + } + + /** + * Same as {@link #get(String)}, with the field name already encoded as UTF-8. Passing a constant array avoids + * encoding the name on every lookup. + * + * @param name the field name, encoded as UTF-8 + * @return the value of the first field with this name, or {@code null} if this object has no such field + */ + public JsonValue get(byte[] name) { int idx = tapeIdx + 1; int endIdx = tape.getMatchingBraceIndex(tapeIdx) - 1; while (idx < endIdx) { @@ -99,7 +109,7 @@ public JsonValue get(String name) { idx = tape.computeNextIndex(valIdx); int stringBufferFromIdx = stringBufferIdx + Integer.BYTES; int stringBufferToIdx = stringBufferFromIdx + len; - if (Arrays.compare(bytes, 0, bytes.length, stringBuffer, stringBufferFromIdx, stringBufferToIdx) == 0) { + if (Arrays.compare(name, 0, name.length, stringBuffer, stringBufferFromIdx, stringBufferToIdx) == 0) { return new JsonValue(tape, valIdx, stringBuffer, buffer); } } @@ -110,6 +120,336 @@ public int getSize() { return tape.getScopeCount(tapeIdx); } + /** + * Returns the index of this value in the parsed document, the starting point for the index-based methods. + *

+ * The index-based methods navigate the whole document that this value belongs to with plain {@code int} indices, + * so a caller can find and read the values it needs without allocating a {@code JsonValue}, an iterator or a + * {@code String} per value. Every index passed to them must come from {@link #index()}, {@link #field}, + * {@link #firstElement} or {@link #advance} on a value of the same document, and stays valid until the parser's + * next parse call. For example, to read {@code doc.items[*].id}: + *

{@code
+     * int items = doc.field(doc.index(), ITEMS);
+     * if (items >= 0 && doc.isArrayAt(items)) {
+     *     int end = doc.scopeEnd(items);
+     *     for (int item = doc.firstElement(items); item >= 0 && item < end; item = doc.advance(item)) {
+     *         int id = doc.isObjectAt(item) ? doc.field(item, ID) : -1;
+     *         if (id >= 0 && doc.isLongAt(id)) {
+     *             consume(doc.longAt(id));
+     *         }
+     *     }
+     * }
+     * }
+ * The methods that require a value of a particular type throw an {@link IllegalArgumentException} when the value + * at the index has another type; the {@code is...At} methods test the type first. + * + * @return the index of this value + */ + public int index() { + return tapeIdx; + } + + /** + * Returns the end of the object or array at {@code idx}: the index just past its last field or element. The + * fields or elements of the container are the values from {@link #firstElement} (for an array) onwards, followed + * with {@link #advance}, up to this index. + * + * @param idx the index of an object or an array + * @return the end index of the container, exclusive + * @throws IllegalArgumentException if the value at {@code idx} is neither an object nor an array + */ + public int scopeEnd(int idx) { + checkContainer(idx); + return tape.getMatchingBraceIndex(idx) - 1; + } + + /** + * Returns the index of the value that follows the value at {@code idx}, skipping its contents if it is an object + * or an array. Within an array this is the next element. Within an object, field names and field values + * alternate: from a field name it moves to its value, and from a value to the next field name. The result equals + * {@link #scopeEnd} of the container when {@code idx} is its last element or field value. + * + * @param idx the index of any value + * @return the index of the following value + */ + public int advance(int idx) { + return tape.computeNextIndex(idx); + } + + /** + * Returns the index of the first element of the array at {@code arrIdx}. + * + * @param arrIdx the index of an array + * @return the index of the first element, or {@code -1} if the array is empty + * @throws IllegalArgumentException if the value at {@code arrIdx} is not an array + */ + public int firstElement(int arrIdx) { + check(arrIdx, START_ARRAY); + int first = arrIdx + 1; + return first < tape.getMatchingBraceIndex(arrIdx) - 1 ? first : -1; + } + + /** + * Looks up a field of the object at {@code objIdx}, like {@link #get(byte[])}, without allocating. + * + * @param objIdx the index of an object + * @param name the field name, encoded as UTF-8 + * @return the index of the value of the first field with this name, or {@code -1} if there is none + * @throws IllegalArgumentException if the value at {@code objIdx} is not an object + */ + public int field(int objIdx, byte[] name) { + check(objIdx, START_OBJECT); + int idx = objIdx + 1; + int endIdx = tape.getMatchingBraceIndex(objIdx) - 1; + while (idx < endIdx) { + int stringBufferIdx = (int) tape.getValue(idx); + int len = IntegerUtils.toInt(stringBuffer, stringBufferIdx); + int valIdx = tape.computeNextIndex(idx); + idx = tape.computeNextIndex(valIdx); + int stringBufferFromIdx = stringBufferIdx + Integer.BYTES; + int stringBufferToIdx = stringBufferFromIdx + len; + if (Arrays.compare(name, 0, name.length, stringBuffer, stringBufferFromIdx, stringBufferToIdx) == 0) { + return valIdx; + } + } + return -1; + } + + /** + * Tests whether the value at {@code idx} is an object. + * + * @param idx the index of any value + * @return {@code true} if the value at {@code idx} is an object + */ + public boolean isObjectAt(int idx) { + return tape.getType(idx) == START_OBJECT; + } + + /** + * Tests whether the value at {@code idx} is an array. + * + * @param idx the index of any value + * @return {@code true} if the value at {@code idx} is an array + */ + public boolean isArrayAt(int idx) { + return tape.getType(idx) == START_ARRAY; + } + + /** + * Tests whether the value at {@code idx} is a string. + * + * @param idx the index of any value + * @return {@code true} if the value at {@code idx} is a string + */ + public boolean isStringAt(int idx) { + return tape.getType(idx) == STRING; + } + + /** + * Tests whether the value at {@code idx} is a number stored as a {@code long}. + * + * @param idx the index of any value + * @return {@code true} if the value at {@code idx} is a number stored as a {@code long}, which is the case for + * every integer literal; see {@link #isLong()} + */ + public boolean isLongAt(int idx) { + return tape.getType(idx) == INT64; + } + + /** + * Tests whether the value at {@code idx} is a number stored as a {@code double}. + * + * @param idx the index of any value + * @return {@code true} if the value at {@code idx} is a number stored as a {@code double}, which is the case for + * every literal with a fraction or an exponent; see {@link #isDouble()} + */ + public boolean isDoubleAt(int idx) { + return tape.getType(idx) == DOUBLE; + } + + /** + * Tests whether the value at {@code idx} is a boolean. + * + * @param idx the index of any value + * @return {@code true} if the value at {@code idx} is {@code true} or {@code false} + */ + public boolean isBooleanAt(int idx) { + char type = tape.getType(idx); + return type == TRUE_VALUE || type == FALSE_VALUE; + } + + /** + * Tests whether the value at {@code idx} is {@code null}. + * + * @param idx the index of any value + * @return {@code true} if the value at {@code idx} is {@code null} + */ + public boolean isNullAt(int idx) { + return tape.getType(idx) == NULL_VALUE; + } + + /** + * Returns the string at {@code idx}. Only the returned {@code String} is allocated; use {@link #stringBytes}, + * {@link #byteOffset} and {@link #byteLength} to read the string without allocating. + * + * @param idx the index of a string + * @return the string + * @throws IllegalArgumentException if the value at {@code idx} is not a string + */ + public String stringAt(int idx) { + check(idx, STRING); + return getString(idx); + } + + /** + * Returns the parser's buffer that holds the decoded strings of the document, as UTF-8. The string at an index + * occupies {@link #byteLength} bytes starting at {@link #byteOffset}; the rest of the array holds other strings + * and internal data. + *

+ * This is the parser's own array, not a copy. Callers must not modify it, and its contents are valid only until + * the parser's next parse call. + * + * @return the parser's string buffer + */ + public byte[] stringBytes() { + return stringBuffer; + } + + /** + * Returns where the string at {@code idx} starts in {@link #stringBytes()}. + * + * @param idx the index of a string + * @return the offset in {@link #stringBytes()} of the first byte of the string at {@code idx} + * @throws IllegalArgumentException if the value at {@code idx} is not a string + */ + public int byteOffset(int idx) { + check(idx, STRING); + return (int) tape.getValue(idx) + Integer.BYTES; + } + + /** + * Returns the length of the string at {@code idx} in {@link #stringBytes()}. + * + * @param idx the index of a string + * @return the length in bytes of the UTF-8 encoding of the string at {@code idx} + * @throws IllegalArgumentException if the value at {@code idx} is not a string + */ + public int byteLength(int idx) { + check(idx, STRING); + return IntegerUtils.toInt(stringBuffer, (int) tape.getValue(idx)); + } + + /** + * Compares the string at {@code idx} with {@code expected} without allocating. + * + * @param idx the index of any value + * @param expected the expected string, encoded as UTF-8 + * @return {@code true} if the value at {@code idx} is a string with exactly these bytes; {@code false} otherwise, + * including when it is not a string + */ + public boolean stringEquals(int idx, byte[] expected) { + if (tape.getType(idx) != STRING) { + return false; + } + int stringBufferIdx = (int) tape.getValue(idx); + int len = IntegerUtils.toInt(stringBuffer, stringBufferIdx); + int from = stringBufferIdx + Integer.BYTES; + return Arrays.equals(expected, 0, expected.length, stringBuffer, from, from + len); + } + + /** + * Returns the integer at {@code idx}. + * + * @param idx the index of a number stored as a {@code long}; see {@link #isLongAt} + * @return the value at {@code idx} + * @throws IllegalArgumentException if the value at {@code idx} is not stored as a {@code long} + */ + public long longAt(int idx) { + check(idx, INT64); + return tape.getInt64Value(idx); + } + + /** + * Returns the floating-point number at {@code idx}. + * + * @param idx the index of a number stored as a {@code double}; see {@link #isDoubleAt} + * @return the value at {@code idx} + * @throws IllegalArgumentException if the value at {@code idx} is not stored as a {@code double} + */ + public double doubleAt(int idx) { + check(idx, DOUBLE); + return tape.getDouble(idx); + } + + /** + * Returns the number at {@code idx} as a {@code double}, whether it is stored as a {@code long} or as a + * {@code double}. An integer whose magnitude exceeds 253 is rounded to the nearest {@code double}, so + * it may not come back exactly; use {@link #longAt} for integers that must be exact. + * + * @param idx the index of a number + * @return the value at {@code idx}, as a {@code double} + * @throws IllegalArgumentException if the value at {@code idx} is not a number + */ + public double numberAt(int idx) { + char type = tape.getType(idx); + if (type == DOUBLE) { + return tape.getDouble(idx); + } + if (type == INT64) { + return tape.getInt64Value(idx); + } + throw wrongType(idx, "a number"); + } + + /** + * Returns the boolean at {@code idx}. + * + * @param idx the index of {@code true} or {@code false} + * @return the value at {@code idx} + * @throws IllegalArgumentException if the value at {@code idx} is not {@code true} or {@code false} + */ + public boolean booleanAt(int idx) { + char type = tape.getType(idx); + if (type == TRUE_VALUE) { + return true; + } + if (type == FALSE_VALUE) { + return false; + } + throw wrongType(idx, "a boolean"); + } + + private void check(int idx, char expectedType) { + if (tape.getType(idx) != expectedType) { + throw wrongType(idx, typeName(expectedType)); + } + } + + private void checkContainer(int idx) { + // '[' (0x5B) and '{' (0x7B) differ only in bit 0x20, and no other tape type becomes '{' when it is set. + if ((tape.getType(idx) | 0x20) != START_OBJECT) { + throw wrongType(idx, "an object or an array"); + } + } + + private IllegalArgumentException wrongType(int idx, String expected) { + return new IllegalArgumentException("Expected " + expected + " at index " + idx + ", but found " + + typeName(tape.getType(idx)) + "."); + } + + private static String typeName(char type) { + return switch (type) { + case START_OBJECT -> "an object"; + case START_ARRAY -> "an array"; + case STRING -> "a string"; + case INT64 -> "an integer"; + case DOUBLE -> "a floating-point number"; + case TRUE_VALUE, FALSE_VALUE -> "a boolean"; + case NULL_VALUE -> "null"; + default -> "no value"; + }; + } + @Override public String toString() { switch (tape.getType(tapeIdx)) { diff --git a/src/test/java/org/simdjson/JsonValueNavigationTest.java b/src/test/java/org/simdjson/JsonValueNavigationTest.java new file mode 100644 index 0000000..01e6b03 --- /dev/null +++ b/src/test/java/org/simdjson/JsonValueNavigationTest.java @@ -0,0 +1,303 @@ +package org.simdjson; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.Iterator; +import java.util.Map; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.simdjson.testutils.TestUtils.toUtf8; + +public class JsonValueNavigationTest { + + @ParameterizedTest + @ValueSource(strings = { + "{\"a\": 1, \"b\": -2.5, \"c\": \"x\", \"d\": true, \"e\": false, \"f\": null, \"g\": {}, \"h\": []}", + "{\"o\": {\"p\": {\"q\": [1, [2, [3, {}]], {\"r\": \"s\"}]}}, \"t\": [[], [[]], {}]}", + "[1, 2.0, \"three\", [4, [5]], {\"six\": 6}, null, true, false, \"\", {}, []]", + "{\"\\u0105\\u0107\": \"\\u03B1\\u03B2\", \"\\u20AC\": [\"\\uD83D\\uDE00\", \"a\\\"b\\\\c\\n\"], \"\": \"empty key\"}", + "{\"big\": 9223372036854775807, \"small\": -9223372036854775808, \"exp\": 1e300, \"tiny\": -4.9e-324}", + "[]", + "{}", + "42", + "-0.5", + "\"root string\"", + "true", + "null" + }) + public void indexNavigationMatchesIterators(String jsonStr) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8(jsonStr); + + // when + JsonValue doc = parser.parse(json, json.length); + + // then + assertSameValue(doc, doc.index(), doc); + } + + @Test + public void nonAsciiKeysAndValues() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"\u0105\u0107\u015B\": \"\u03B1\u03B2\u03B3\", \"\\u20AC\": \"\\uD83D\\uDE00\"}"); + JsonValue doc = parser.parse(json, json.length); + + // when + int first = doc.field(doc.index(), toUtf8("\u0105\u0107\u015B")); + int second = doc.field(doc.index(), toUtf8("\u20AC")); + + // then + assertThat(doc.stringAt(first)).isEqualTo("\u03B1\u03B2\u03B3"); + assertThat(doc.byteLength(first)).isEqualTo(6); + assertThat(doc.stringEquals(first, toUtf8("\u03B1\u03B2\u03B3"))).isTrue(); + assertThat(doc.stringAt(second)).isEqualTo("\uD83D\uDE00"); + assertThat(doc.byteLength(second)).isEqualTo(4); + assertThat(doc.get(toUtf8("\u20AC")).asString()).isEqualTo("\uD83D\uDE00"); + } + + @Test + public void missingFields() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": {\"b\": 1}, \"e\": {}}"); + JsonValue doc = parser.parse(json, json.length); + int a = doc.field(doc.index(), toUtf8("a")); + int e = doc.field(doc.index(), toUtf8("e")); + + // expect + assertThat(doc.field(doc.index(), toUtf8("b"))).isEqualTo(-1); + assertThat(doc.field(doc.index(), toUtf8("A"))).isEqualTo(-1); + assertThat(doc.field(doc.index(), toUtf8("ab"))).isEqualTo(-1); + assertThat(doc.field(doc.index(), new byte[0])).isEqualTo(-1); + assertThat(doc.field(a, toUtf8("c"))).isEqualTo(-1); + assertThat(doc.field(e, toUtf8("b"))).isEqualTo(-1); + assertThat(doc.get(toUtf8("b"))).isNull(); + assertThat(doc.get("b")).isNull(); + } + + @Test + public void firstOccurrenceOfDuplicateField() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"a\": 1, \"a\": 2}"); + JsonValue doc = parser.parse(json, json.length); + + // when + int a = doc.field(doc.index(), toUtf8("a")); + + // then + assertThat(doc.longAt(a)).isEqualTo(1); + assertThat(a).isEqualTo(doc.get("a").index()); + } + + @Test + public void emptyContainers() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"o\": {}, \"a\": [], \"n\": [[]]}"); + JsonValue doc = parser.parse(json, json.length); + int o = doc.field(doc.index(), toUtf8("o")); + int a = doc.field(doc.index(), toUtf8("a")); + int n = doc.field(doc.index(), toUtf8("n")); + + // expect + assertThat(doc.isObjectAt(o)).isTrue(); + assertThat(doc.field(o, toUtf8("x"))).isEqualTo(-1); + assertThat(doc.isArrayAt(a)).isTrue(); + assertThat(doc.firstElement(a)).isEqualTo(-1); + assertThat(countElements(doc, a)).isEqualTo(0); + assertThat(countElements(doc, n)).isEqualTo(1); + int inner = doc.firstElement(n); + assertThat(doc.isArrayAt(inner)).isTrue(); + assertThat(doc.firstElement(inner)).isEqualTo(-1); + assertThat(doc.advance(inner)).isEqualTo(doc.scopeEnd(n)); + } + + @Test + public void numberAtLosesPrecisionAboveTwoToThe53() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[9007199254740992, 9007199254740993]"); + JsonValue doc = parser.parse(json, json.length); + int first = doc.firstElement(doc.index()); + int second = doc.advance(first); + + // expect + assertThat(doc.longAt(first)).isEqualTo(9007199254740992L); + assertThat(doc.numberAt(first)).isEqualTo(9007199254740992.0); + assertThat(doc.longAt(second)).isEqualTo(9007199254740993L); + assertThat(doc.numberAt(second)).isEqualTo(9007199254740992.0); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "field | a | Expected an object at index 6, but found an array.", + "field | s | Expected an object at index 9, but found a string.", + "firstElement | o | Expected an array at index 3, but found an object.", + "firstElement | n | Expected an array at index 19, but found null.", + "scopeEnd | s | Expected an object or an array at index 9, but found a string.", + "scopeEnd | l | Expected an object or an array at index 11, but found an integer.", + "stringAt | l | Expected a string at index 11, but found an integer.", + "byteOffset | o | Expected a string at index 3, but found an object.", + "byteLength | t | Expected a string at index 17, but found a boolean.", + "longAt | d | Expected an integer at index 14, but found a floating-point number.", + "longAt | s | Expected an integer at index 9, but found a string.", + "doubleAt | l | Expected a floating-point number at index 11, but found an integer.", + "numberAt | s | Expected a number at index 9, but found a string.", + "numberAt | n | Expected a number at index 19, but found null.", + "booleanAt | n | Expected a boolean at index 19, but found null.", + "booleanAt | l | Expected a boolean at index 11, but found an integer." + }) + public void wrongTypeIndex(String method, String fieldName, String expectedMessage) { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("{\"o\": {}, \"a\": [], \"s\": \"x\", \"l\": 1, \"d\": 1.5, \"t\": true, \"n\": null}"); + JsonValue doc = parser.parse(json, json.length); + int idx = doc.field(doc.index(), toUtf8(fieldName)); + + // when + IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> { + switch (method) { + case "field" -> doc.field(idx, toUtf8("x")); + case "firstElement" -> doc.firstElement(idx); + case "scopeEnd" -> doc.scopeEnd(idx); + case "stringAt" -> doc.stringAt(idx); + case "byteOffset" -> doc.byteOffset(idx); + case "byteLength" -> doc.byteLength(idx); + case "longAt" -> doc.longAt(idx); + case "doubleAt" -> doc.doubleAt(idx); + case "numberAt" -> doc.numberAt(idx); + case "booleanAt" -> doc.booleanAt(idx); + default -> throw new IllegalStateException(method); + } + }); + + // then + assertThat(ex).hasMessage(expectedMessage); + } + + @Test + public void stringEqualsOnOtherTypesIsFalse() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] json = toUtf8("[\"1\", 1, null, [], {}, true]"); + JsonValue doc = parser.parse(json, json.length); + int end = doc.scopeEnd(doc.index()); + byte[] one = toUtf8("1"); + + // when + int matches = 0; + for (int e = doc.firstElement(doc.index()); e >= 0 && e < end; e = doc.advance(e)) { + if (doc.stringEquals(e, one)) { + matches++; + } + } + + // then + assertThat(matches).isEqualTo(1); + } + + @Test + public void stringBytesIsTheParserBuffer() { + // given + SimdJsonParser parser = new SimdJsonParser(); + byte[] first = toUtf8("[\"abc\"]"); + byte[] second = toUtf8("[\"xyz\"]"); + + // when + JsonValue firstDoc = parser.parse(first, first.length); + byte[] firstBuffer = firstDoc.stringBytes(); + int firstIdx = firstDoc.firstElement(firstDoc.index()); + int offset = firstDoc.byteOffset(firstIdx); + int length = firstDoc.byteLength(firstIdx); + JsonValue secondDoc = parser.parse(second, second.length); + + // then + assertThat(secondDoc.stringBytes()).isSameAs(firstBuffer); + assertThat(new String(firstBuffer, offset, length, UTF_8)).isEqualTo("xyz"); + } + + private static void assertSameValue(JsonValue doc, int idx, JsonValue expected) { + assertThat(idx).isEqualTo(expected.index()); + assertThat(doc.isObjectAt(idx)).isEqualTo(expected.isObject()); + assertThat(doc.isArrayAt(idx)).isEqualTo(expected.isArray()); + assertThat(doc.isStringAt(idx)).isEqualTo(expected.isString()); + assertThat(doc.isLongAt(idx)).isEqualTo(expected.isLong()); + assertThat(doc.isDoubleAt(idx)).isEqualTo(expected.isDouble()); + assertThat(doc.isBooleanAt(idx)).isEqualTo(expected.isBoolean()); + assertThat(doc.isNullAt(idx)).isEqualTo(expected.isNull()); + if (expected.isObject()) { + assertSameObject(doc, idx, expected); + } else if (expected.isArray()) { + assertSameArray(doc, idx, expected); + } else if (expected.isString()) { + String value = expected.asString(); + assertThat(doc.stringAt(idx)).isEqualTo(value); + assertThat(new String(doc.stringBytes(), doc.byteOffset(idx), doc.byteLength(idx), UTF_8)).isEqualTo(value); + assertThat(doc.stringEquals(idx, toUtf8(value))).isTrue(); + assertThat(doc.stringEquals(idx, toUtf8(value + "x"))).isFalse(); + } else if (expected.isLong()) { + assertThat(doc.longAt(idx)).isEqualTo(expected.asLong()); + assertThat(doc.numberAt(idx)).isEqualTo((double) expected.asLong()); + } else if (expected.isDouble()) { + assertThat(doc.doubleAt(idx)).isEqualTo(expected.asDouble()); + assertThat(doc.numberAt(idx)).isEqualTo(expected.asDouble()); + } else if (expected.isBoolean()) { + assertThat(doc.booleanAt(idx)).isEqualTo(expected.asBoolean()); + } + } + + private static void assertSameObject(JsonValue doc, int idx, JsonValue expected) { + int end = doc.scopeEnd(idx); + int previousValue = -1; + Iterator> it = expected.objectIterator(); + while (it.hasNext()) { + Map.Entry entry = it.next(); + byte[] name = toUtf8(entry.getKey()); + int value = doc.field(idx, name); + assertThat(value).isEqualTo(entry.getValue().index()); + assertThat(expected.get(name).index()).isEqualTo(expected.get(entry.getKey()).index()); + if (previousValue >= 0) { + assertThat(doc.advance(doc.advance(previousValue))).isEqualTo(value); + } + assertThat(value).isLessThan(end); + assertSameValue(doc, value, entry.getValue()); + previousValue = value; + } + if (previousValue >= 0) { + assertThat(doc.advance(previousValue)).isEqualTo(end); + } + } + + private static void assertSameArray(JsonValue doc, int idx, JsonValue expected) { + int end = doc.scopeEnd(idx); + Iterator it = expected.arrayIterator(); + int element = doc.firstElement(idx); + if (!it.hasNext()) { + assertThat(element).isEqualTo(-1); + return; + } + while (it.hasNext()) { + assertThat(element).isLessThan(end); + assertSameValue(doc, element, it.next()); + element = doc.advance(element); + } + assertThat(element).isEqualTo(end); + } + + private static int countElements(JsonValue doc, int arrIdx) { + int count = 0; + int end = doc.scopeEnd(arrIdx); + for (int e = doc.firstElement(arrIdx); e >= 0 && e < end; e = doc.advance(e)) { + count++; + } + return count; + } +} From 09a93d7a7c4bb166014af0cd64c5a17d2dc46a7a Mon Sep 17 00:00:00 2001 From: Morris Meyer Date: Sat, 21 Nov 2026 20:40:08 +0000 Subject: [PATCH 6/9] Allow a parser to skip UTF-8 validation of trusted input Every parse validates its input as UTF-8 before indexing it. When the input is known to be valid, for example because it was produced or already checked by a trusted component, that pass is redundant. The new constructor SimdJsonParser(capacity, maxDepth, validateUtf8) creates a parser that skips it when validateUtf8 is false; invalid UTF-8 then goes undetected. The existing constructors keep validating. --- .../java/org/simdjson/SimdJsonParser.java | 29 ++- .../simdjson/Utf8ValidationOptionTest.java | 167 ++++++++++++++++++ 2 files changed, 192 insertions(+), 4 deletions(-) create mode 100644 src/test/java/org/simdjson/Utf8ValidationOptionTest.java diff --git a/src/main/java/org/simdjson/SimdJsonParser.java b/src/main/java/org/simdjson/SimdJsonParser.java index 02853e2..6a13ed2 100644 --- a/src/main/java/org/simdjson/SimdJsonParser.java +++ b/src/main/java/org/simdjson/SimdJsonParser.java @@ -12,12 +12,31 @@ public class SimdJsonParser { private final SchemaBasedJsonIterator schemaBasedJsonIterator; private final OnDemandJsonIterator onDemandJsonIterator; private final byte[] paddedBuffer; + private final boolean validateUtf8; public SimdJsonParser() { this(DEFAULT_CAPACITY, DEFAULT_MAX_DEPTH); } public SimdJsonParser(int capacity, int maxDepth) { + this(capacity, maxDepth, true); + } + + /** + * Creates a parser that may skip UTF-8 validation. + *

+ * By default every parse method first checks that the input is valid UTF-8 and rejects it otherwise. With + * {@code validateUtf8} set to {@code false} that pass is skipped, which saves its cost when the input is already + * known to be valid UTF-8, for example because it was validated or produced by a trusted component. The input is + * then trusted: invalid UTF-8 is not detected, and strings decoded from it may be malformed UTF-8. The rest of the + * parsing is unchanged. + * + * @param capacity the size of the largest document this parser can parse, in bytes + * @param maxDepth the maximum nesting depth of objects and arrays + * @param validateUtf8 {@code true} to reject input that is not valid UTF-8, {@code false} to skip the check + */ + public SimdJsonParser(int capacity, int maxDepth, boolean validateUtf8) { + this.validateUtf8 = validateUtf8; bitIndexes = new BitIndexes(capacity); byte[] stringBuffer = new byte[capacity]; jsonIterator = new JsonIterator(bitIndexes, stringBuffer, capacity, maxDepth, PADDING); @@ -28,8 +47,8 @@ public SimdJsonParser(int capacity, int maxDepth) { } /** - * Prepares on-demand parsing of the first {@code len} bytes of {@code buffer}: validates the input as UTF-8, - * indexes its structural characters, and returns a forward-only cursor that decodes values only when asked. No + * Prepares on-demand parsing of the first {@code len} bytes of {@code buffer}: validates the input as UTF-8 + * (unless the parser was created without validation), indexes its structural characters, and returns a forward-only cursor that decodes values only when asked. No * tape is built. See {@link OnDemandJsonIterator} for how to use the cursor. *

* The parser returns the same cursor instance on every call. It is valid until the next call to any parse method @@ -40,7 +59,7 @@ public SimdJsonParser(int capacity, int maxDepth) { * cursor is in use * @param len the length of the document in bytes * @return the cursor, positioned before the root value - * @throws JsonParsingException if the input is not valid UTF-8, contains no structural element, or has an + * @throws JsonParsingException if the input is not valid UTF-8 (when validated), contains no structural element, or has an * unclosed string or unescaped control characters in a string */ public OnDemandJsonIterator parseOnDemand(byte[] buffer, int len) { @@ -79,7 +98,9 @@ private void reset() { } private void stage1(byte[] buffer, int length) { - Utf8Validator.validate(buffer, length); + if (validateUtf8) { + Utf8Validator.validate(buffer, length); + } indexer.index(buffer, length); } } diff --git a/src/test/java/org/simdjson/Utf8ValidationOptionTest.java b/src/test/java/org/simdjson/Utf8ValidationOptionTest.java new file mode 100644 index 0000000..f029c1c --- /dev/null +++ b/src/test/java/org/simdjson/Utf8ValidationOptionTest.java @@ -0,0 +1,167 @@ +package org.simdjson; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.simdjson.OnDemandJsonIterator.IteratorResult; +import org.simdjson.schemas.RecordWithStringArrayField; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.simdjson.testutils.TestUtils.toUtf8; + +public class Utf8ValidationOptionTest { + + private static final int CAPACITY = 1024; + private static final int MAX_DEPTH = 64; + + // A string containing 0xFF, which never occurs in UTF-8. + private static final byte[] INVALID_UTF8 = {'{', '"', 'f', 'i', 'e', 'l', 'd', '"', ':', '[', '"', 'a', (byte) 0xFF, 'b', '"', ']', '}'}; + + @ParameterizedTest + @ValueSource(strings = { + "{\"field\": [\"abc\", \"\\u0105\\u20AC\", \"\\uD83D\\uDE00\", \"\"]}", + "{\"field\": [\"\u0105\u0107\u015B\", \"\u03B1\u03B2\u03B3\", \"\uD83D\uDE00 x\"]}", + "{\"field\": [], \"other\": {\"a\": [1, 2.5, true, null]}}" + }) + public void validDocumentParsesIdenticallyWithAndWithoutValidation(String jsonStr) { + // given + SimdJsonParser validating = new SimdJsonParser(CAPACITY, MAX_DEPTH, true); + SimdJsonParser trusting = new SimdJsonParser(CAPACITY, MAX_DEPTH, false); + byte[] json = toUtf8(jsonStr); + + // when + String validatingDom = render(validating.parse(json, json.length)); + String trustingDom = render(trusting.parse(json, json.length)); + String[] validatingSchema = validating.parse(json, json.length, RecordWithStringArrayField.class).field(); + String[] trustingSchema = trusting.parse(json, json.length, RecordWithStringArrayField.class).field(); + List validatingOnDemand = onDemandStrings(validating, json, json.length); + List trustingOnDemand = onDemandStrings(trusting, json, json.length); + + // then + assertThat(trustingDom).isEqualTo(validatingDom); + assertThat(trustingSchema).containsExactly(validatingSchema); + assertThat(trustingOnDemand).isEqualTo(validatingOnDemand); + assertThat(validatingOnDemand).containsExactly(validatingSchema); + } + + @Test + public void defaultConstructorsValidate() { + // given + SimdJsonParser defaultParser = new SimdJsonParser(); + SimdJsonParser sizedParser = new SimdJsonParser(CAPACITY, MAX_DEPTH); + + // when + JsonParsingException defaultEx = assertThrows(JsonParsingException.class, () -> defaultParser.parse(INVALID_UTF8, INVALID_UTF8.length)); + JsonParsingException sizedEx = assertThrows(JsonParsingException.class, () -> sizedParser.parse(INVALID_UTF8, INVALID_UTF8.length)); + + // then + assertThat(defaultEx).hasMessage("The input is not valid UTF-8"); + assertThat(sizedEx).hasMessage("The input is not valid UTF-8"); + } + + @Test + public void invalidUtf8IsRejectedWithValidation() { + // given + SimdJsonParser parser = new SimdJsonParser(CAPACITY, MAX_DEPTH, true); + + // when + JsonParsingException domEx = assertThrows(JsonParsingException.class, + () -> parser.parse(INVALID_UTF8, INVALID_UTF8.length)); + JsonParsingException schemaEx = assertThrows(JsonParsingException.class, + () -> parser.parse(INVALID_UTF8, INVALID_UTF8.length, RecordWithStringArrayField.class)); + JsonParsingException onDemandEx = assertThrows(JsonParsingException.class, + () -> parser.parseOnDemand(INVALID_UTF8, INVALID_UTF8.length)); + + // then + assertThat(domEx).hasMessage("The input is not valid UTF-8"); + assertThat(schemaEx).hasMessage("The input is not valid UTF-8"); + assertThat(onDemandEx).hasMessage("The input is not valid UTF-8"); + } + + @Test + public void invalidUtf8IsNotRejectedWithoutValidation() { + // given + SimdJsonParser parser = new SimdJsonParser(CAPACITY, MAX_DEPTH, false); + byte[] expected = {'a', (byte) 0xFF, 'b'}; + + // when + JsonValue dom = parser.parse(INVALID_UTF8, INVALID_UTF8.length); + int string = dom.firstElement(dom.field(dom.index(), toUtf8("field"))); + byte[] domBytes = Arrays.copyOfRange(dom.stringBytes(), dom.byteOffset(string), dom.byteOffset(string) + dom.byteLength(string)); + String[] schema = parser.parse(INVALID_UTF8, INVALID_UTF8.length, RecordWithStringArrayField.class).field(); + OnDemandJsonIterator it = parser.parseOnDemand(INVALID_UTF8, INVALID_UTF8.length); + byte[] onDemandBuffer = new byte[16 + OnDemandJsonIterator.STRING_BUFFER_PADDING]; + assertThat(it.startIteratingRootObject()).isEqualTo(IteratorResult.NOT_EMPTY); + it.getFieldName(onDemandBuffer); + it.moveToFieldValue(); + assertThat(it.startIteratingArray()).isEqualTo(IteratorResult.NOT_EMPTY); + int onDemandLength = it.getString(onDemandBuffer); + + // then + assertThat(domBytes).isEqualTo(expected); + assertThat(schema).hasSize(1); + assertThat(Arrays.copyOf(onDemandBuffer, onDemandLength)).isEqualTo(expected); + assertThat(it.nextArrayElement()).isFalse(); + assertThat(it.nextObjectField()).isFalse(); + } + + private static List onDemandStrings(SimdJsonParser parser, byte[] json, int len) { + List strings = new ArrayList<>(); + byte[] buffer = new byte[CAPACITY + OnDemandJsonIterator.STRING_BUFFER_PADDING]; + OnDemandJsonIterator it = parser.parseOnDemand(json, len); + if (it.startIteratingRootObject() == IteratorResult.NOT_EMPTY) { + do { + int nameLength = it.getFieldName(buffer); + it.moveToFieldValue(); + boolean field = new String(buffer, 0, nameLength, UTF_8).equals("field"); + if (field && it.startIteratingArray() == IteratorResult.NOT_EMPTY) { + do { + int length = it.getString(buffer); + strings.add(new String(buffer, 0, length, UTF_8)); + } while (it.nextArrayElement()); + } else if (!field) { + it.skipChild(); + } + } while (it.nextObjectField()); + } + return strings; + } + + private static String render(JsonValue value) { + StringBuilder sb = new StringBuilder(); + render(value, sb); + return sb.toString(); + } + + private static void render(JsonValue value, StringBuilder sb) { + if (value.isObject()) { + sb.append('{'); + Iterator> it = value.objectIterator(); + while (it.hasNext()) { + Map.Entry field = it.next(); + sb.append(field.getKey()).append(':'); + render(field.getValue(), sb); + sb.append(','); + } + sb.append('}'); + } else if (value.isArray()) { + sb.append('['); + Iterator it = value.arrayIterator(); + while (it.hasNext()) { + render(it.next(), sb); + sb.append(','); + } + sb.append(']'); + } else { + sb.append(value.isString() ? "s:" : "v:").append(value); + } + } +} From 64c815ba178bc3c812c88ac62c75451a41ee4c8c Mon Sep 17 00:00:00 2001 From: Morris Meyer Date: Sat, 21 Nov 2026 20:40:08 +0000 Subject: [PATCH 7/9] Add a Synthea FHIR bundle extraction benchmark and verifier SyntheaBundleBenchmark extracts a fixed set of fields from a corpus of Synthea FHIR bundles with each way of reading a document: domGetString (get(String) and iterators), domGetBytes (get(byte[])), domIndex (index-based JsonValue navigation), onDemand (parseOnDemand), schemaBased (records), and domParseOnly as the parsing baseline. Every extraction mode folds the same values into a checksum, and the trial setup refuses to measure if the modes disagree on the first files. SyntheaBundleVerifier runs all extraction modes over the whole corpus and reports whether they agree. No data is shipped: the corpus is a directory of generated bundles selected with -Dsynthea.dir, and -Dsynthea.validateUtf8=false selects parsers that skip UTF-8 validation. --- .../synthea/SyntheaBundleBenchmark.java | 133 +++ .../synthea/SyntheaBundleVerifier.java | 134 +++ .../org/simdjson/synthea/SyntheaChecksum.java | 127 +++ .../org/simdjson/synthea/SyntheaCorpus.java | 220 +++++ .../simdjson/synthea/SyntheaExtractor.java | 823 ++++++++++++++++++ .../org/simdjson/synthea/SyntheaSchema.java | 49 ++ 6 files changed, 1486 insertions(+) create mode 100644 src/jmh/java/org/simdjson/synthea/SyntheaBundleBenchmark.java create mode 100644 src/jmh/java/org/simdjson/synthea/SyntheaBundleVerifier.java create mode 100644 src/jmh/java/org/simdjson/synthea/SyntheaChecksum.java create mode 100644 src/jmh/java/org/simdjson/synthea/SyntheaCorpus.java create mode 100644 src/jmh/java/org/simdjson/synthea/SyntheaExtractor.java create mode 100644 src/jmh/java/org/simdjson/synthea/SyntheaSchema.java diff --git a/src/jmh/java/org/simdjson/synthea/SyntheaBundleBenchmark.java b/src/jmh/java/org/simdjson/synthea/SyntheaBundleBenchmark.java new file mode 100644 index 0000000..5611b00 --- /dev/null +++ b/src/jmh/java/org/simdjson/synthea/SyntheaBundleBenchmark.java @@ -0,0 +1,133 @@ +package org.simdjson.synthea; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Level; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.infra.Blackhole; +import org.simdjson.SimdJsonParser; + +import java.util.concurrent.TimeUnit; + +/** + * Extracts a fixed set of fields from Synthea FHIR bundles (see {@link SyntheaExtractor}) with each + * parsing mode. + *

+ * One benchmark operation is one pass over the whole corpus, so the score (average time per operation) + * converts to throughput as {@code totalBytes / score} and {@code files / score}; both numbers are + * printed by the trial setup. With {@code -t N}, each of the N threads makes its own full pass per + * operation, with its own parser, over the shared read-only corpus. + *

+ * The corpus is selected by system properties of the forked JVM; see {@link SyntheaCorpus}. The property + * {@code synthea.validateUtf8} (default {@code true}) selects whether the parsers validate UTF-8; the trial setup + * prints the setting. Before any + * measurement, the trial setup checks that all modes agree on the first few files and refuses to run + * if they do not. + */ +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +public class SyntheaBundleBenchmark { + + private static final int AGREEMENT_CHECK_FILES = 4; + + @State(Scope.Benchmark) + public static class CorpusState { + + SyntheaCorpus corpus; + boolean validateUtf8; + + @Setup(Level.Trial) + public void setup() { + corpus = SyntheaCorpus.fromSystemProperties(); + corpus.printSummary(System.out); + validateUtf8 = SyntheaExtractor.validateUtf8FromSystemProperties(); + System.out.println(SyntheaExtractor.VALIDATE_UTF8_PROPERTY + "=" + validateUtf8); + SyntheaBundleVerifier.Report report = + SyntheaBundleVerifier.verify(corpus, Math.min(AGREEMENT_CHECK_FILES, corpus.size()), validateUtf8); + report.print(System.out); + if (!report.agree()) { + throw new IllegalStateException("Parsing modes disagree on the first files of the corpus; " + + "refusing to measure. Run SyntheaBundleVerifier for details."); + } + } + } + + @State(Scope.Thread) + public static class ExtractorState { + + SyntheaExtractor extractor; + + @Setup(Level.Trial) + public void setup(CorpusState corpusState) { + extractor = new SyntheaExtractor(corpusState.corpus.maxLength(), corpusState.validateUtf8); + } + } + + @Benchmark + public void domParseOnly(CorpusState corpusState, ExtractorState state, Blackhole blackhole) { + SyntheaCorpus corpus = corpusState.corpus; + SimdJsonParser parser = state.extractor.parser(); + for (int i = 0; i < corpus.size(); i++) { + blackhole.consume(parser.parse(corpus.document(i), corpus.length(i))); + } + } + + @Benchmark + public long domGetString(CorpusState corpusState, ExtractorState state) { + SyntheaCorpus corpus = corpusState.corpus; + SyntheaExtractor extractor = state.extractor; + extractor.sum().reset(); + for (int i = 0; i < corpus.size(); i++) { + extractor.domGetString(corpus.document(i), corpus.length(i)); + } + return extractor.sum().checksum(); + } + + @Benchmark + public long schemaBased(CorpusState corpusState, ExtractorState state) { + SyntheaCorpus corpus = corpusState.corpus; + SyntheaExtractor extractor = state.extractor; + extractor.sum().reset(); + for (int i = 0; i < corpus.size(); i++) { + extractor.schemaBased(corpus.document(i), corpus.length(i)); + } + return extractor.sum().checksum(); + } + + @Benchmark + public long domGetBytes(CorpusState corpusState, ExtractorState state) { + SyntheaCorpus corpus = corpusState.corpus; + SyntheaExtractor extractor = state.extractor; + extractor.sum().reset(); + for (int i = 0; i < corpus.size(); i++) { + extractor.domGetBytes(corpus.document(i), corpus.length(i)); + } + return extractor.sum().checksum(); + } + + @Benchmark + public long domIndex(CorpusState corpusState, ExtractorState state) { + SyntheaCorpus corpus = corpusState.corpus; + SyntheaExtractor extractor = state.extractor; + extractor.sum().reset(); + for (int i = 0; i < corpus.size(); i++) { + extractor.domIndex(corpus.document(i), corpus.length(i)); + } + return extractor.sum().checksum(); + } + + @Benchmark + public long onDemand(CorpusState corpusState, ExtractorState state) { + SyntheaCorpus corpus = corpusState.corpus; + SyntheaExtractor extractor = state.extractor; + extractor.sum().reset(); + for (int i = 0; i < corpus.size(); i++) { + extractor.onDemand(corpus.document(i), corpus.length(i)); + } + return extractor.sum().checksum(); + } +} diff --git a/src/jmh/java/org/simdjson/synthea/SyntheaBundleVerifier.java b/src/jmh/java/org/simdjson/synthea/SyntheaBundleVerifier.java new file mode 100644 index 0000000..3415084 --- /dev/null +++ b/src/jmh/java/org/simdjson/synthea/SyntheaBundleVerifier.java @@ -0,0 +1,134 @@ +package org.simdjson.synthea; + +import org.simdjson.JsonValue; +import org.simdjson.SimdJsonParser; + +import java.io.PrintStream; +import java.util.EnumMap; +import java.util.Iterator; +import java.util.Map; +import java.util.TreeMap; + +/** + * Runs every {@link SyntheaExtractor.Mode} over the corpus and checks that they all compute the same + * checksum and resource counts. Each mode is run twice with the same parser, to also catch state that + * leaks from one parse into the next. Any failure, or any disagreement, makes the verification fail. + *

+ * Usage (no JMH involved): + *

+ *   java --add-modules jdk.incubator.vector -Dsynthea.dir=DIR [-Dsynthea.maxFiles=N] [-Dsynthea.validateUtf8=false] \
+ *        -cp build/libs/*-jmh.jar org.simdjson.synthea.SyntheaBundleVerifier
+ * 
+ * Exit status 0 when all modes agree, 1 otherwise. + */ +public final class SyntheaBundleVerifier { + + private SyntheaBundleVerifier() { + } + + public static void main(String[] args) { + SyntheaCorpus corpus = SyntheaCorpus.fromSystemProperties(); + boolean validateUtf8 = SyntheaExtractor.validateUtf8FromSystemProperties(); + corpus.printSummary(System.out); + System.out.println("java.vm.version=" + System.getProperty("java.vm.version") + + " " + SyntheaExtractor.VALIDATE_UTF8_PROPERTY + "=" + validateUtf8); + Report report = verify(corpus, corpus.size(), validateUtf8); + report.print(System.out); + printResourceTypes(corpus, validateUtf8, System.out); + System.out.println(report.agree() ? "VERIFY PASS" : "VERIFY FAIL"); + System.exit(report.agree() ? 0 : 1); + } + + /** Runs all modes over the first {@code files} documents of the corpus, with parsers that validate UTF-8 or not. */ + public static Report verify(SyntheaCorpus corpus, int files, boolean validateUtf8) { + Map results = new EnumMap<>(SyntheaExtractor.Mode.class); + Map failures = new EnumMap<>(SyntheaExtractor.Mode.class); + for (SyntheaExtractor.Mode mode : SyntheaExtractor.Mode.values()) { + SyntheaExtractor extractor = new SyntheaExtractor(corpus.maxLength(), validateUtf8); + SyntheaChecksum.Result first = null; + for (int pass = 0; pass < 2; pass++) { + extractor.sum().reset(); + int i = 0; + try { + for (; i < files; i++) { + extractor.run(mode, corpus.document(i), corpus.length(i)); + } + } catch (RuntimeException e) { + failures.put(mode, "pass " + pass + ", file " + corpus.name(i) + ": " + e); + break; + } + SyntheaChecksum.Result result = SyntheaChecksum.Result.of(extractor.sum()); + if (first == null) { + first = result; + } else if (!first.sameAs(result)) { + failures.put(mode, "second pass with the same parser differs: " + first + " vs " + result); + } + } + if (!failures.containsKey(mode)) { + results.put(mode, first); + } + } + return new Report(files, results, failures); + } + + public record Report(int files, + Map results, + Map failures) { + + public boolean agree() { + if (!failures.isEmpty()) { + return false; + } + SyntheaChecksum.Result reference = results.get(SyntheaExtractor.Mode.DOM_GET_STRING); + if (reference == null) { + return false; + } + for (SyntheaChecksum.Result result : results.values()) { + if (!reference.sameAs(result)) { + return false; + } + } + return true; + } + + public void print(PrintStream out) { + out.println("Verified " + files + " file(s):"); + SyntheaChecksum.Result reference = results.get(SyntheaExtractor.Mode.DOM_GET_STRING); + for (SyntheaExtractor.Mode mode : SyntheaExtractor.Mode.values()) { + String line; + if (failures.containsKey(mode)) { + line = "FAILED " + failures.get(mode); + } else { + SyntheaChecksum.Result result = results.get(mode); + boolean same = reference != null && reference.sameAs(result); + line = (same ? "OK " : "MISMATCH ") + result; + } + out.printf(" %-14s %s%n", mode.label(), line); + } + } + } + + /** Informational: resource counts for every resourceType, not only the four the extraction reads. */ + private static void printResourceTypes(SyntheaCorpus corpus, boolean validateUtf8, PrintStream out) { + SimdJsonParser parser = new SimdJsonParser(corpus.maxLength() + SyntheaCorpus.PADDING, 1024, validateUtf8); + Map counts = new TreeMap<>(); + for (int i = 0; i < corpus.size(); i++) { + JsonValue bundle = parser.parse(corpus.document(i), corpus.length(i)); + JsonValue entries = bundle.isObject() ? bundle.get("entry") : null; + if (entries == null || !entries.isArray()) { + continue; + } + Iterator it = entries.arrayIterator(); + while (it.hasNext()) { + JsonValue entry = it.next(); + JsonValue resource = entry.isObject() ? entry.get("resource") : null; + if (resource != null && resource.isObject()) { + JsonValue type = resource.get("resourceType"); + String name = type != null && type.isString() ? type.asString() : ""; + counts.merge(name, 1L, Long::sum); + } + } + } + out.println("All resource types: " + counts); + } +} diff --git a/src/jmh/java/org/simdjson/synthea/SyntheaChecksum.java b/src/jmh/java/org/simdjson/synthea/SyntheaChecksum.java new file mode 100644 index 0000000..44a7f00 --- /dev/null +++ b/src/jmh/java/org/simdjson/synthea/SyntheaChecksum.java @@ -0,0 +1,127 @@ +package org.simdjson.synthea; + +import java.util.Arrays; + +import static java.nio.charset.StandardCharsets.UTF_8; + +/** + * Order-sensitive 64-bit checksum over the values extracted from a corpus, plus resource counts per type. + *

+ * Each extracted value is first reduced to a 64-bit value hash, then folded into the running checksum: + *

    + *
  • string: FNV-1a over its UTF-8 bytes, finished with the length ({@link #hashString});
  • + *
  • number: the IEEE-754 bits of the value as a {@code double}, with -0.0 mapped to 0.0 + * ({@link #hashNumber}); the JSON literals {@code 5}, {@code 5.0} and {@code 5e0} therefore hash + * identically;
  • + *
  • a field that is missing, {@code null}, or of an unexpected JSON type: the constant {@link #ABSENT}.
  • + *
+ * Resources are folded in document order. Within a resource the values are folded in a fixed order that + * does not depend on the order of keys in the JSON (see {@link SyntheaExtractor}). + */ +public final class SyntheaChecksum { + + public static final int PATIENT = 0; + public static final int ENCOUNTER = 1; + public static final int OBSERVATION = 2; + public static final int CONDITION = 3; + public static final int OTHER = 4; + static final String[] TYPE_NAMES = {"Patient", "Encounter", "Observation", "Condition", "other"}; + + private static final long FNV_OFFSET = 0xcbf29ce484222325L; + private static final long FNV_PRIME = 0x100000001b3L; + private static final long NUMBER_SEED = 0x6a09e667f3bcc909L; + private static final long FOLD_MULTIPLIER = 0x9e3779b97f4a7c15L; + + public static final long ABSENT = mix(0xbb67ae8584caa73bL); + + private final long[] counts = new long[TYPE_NAMES.length]; + private long checksum; + + public void reset() { + checksum = 0; + Arrays.fill(counts, 0); + } + + public void fold(long valueHash) { + checksum = (Long.rotateLeft(checksum, 23) ^ valueHash) * FOLD_MULTIPLIER; + } + + public void count(int type) { + counts[type]++; + } + + public long checksum() { + return checksum; + } + + public long[] counts() { + return counts.clone(); + } + + public static long hashString(byte[] bytes, int offset, int length) { + long h = FNV_OFFSET; + for (int i = offset; i < offset + length; i++) { + h ^= bytes[i] & 0xFF; + h *= FNV_PRIME; + } + return mix(h ^ length); + } + + /** Same value as {@link #hashString(byte[], int, int)} over {@code s.getBytes(UTF_8)}. */ + public static long hashString(String s) { + long h = FNV_OFFSET; + int length = s.length(); + for (int i = 0; i < length; i++) { + char c = s.charAt(i); + if (c >= 0x80) { + // Not ASCII: UTF-16 chars are no longer UTF-8 bytes, so encode. + byte[] bytes = s.getBytes(UTF_8); + return hashString(bytes, 0, bytes.length); + } + h ^= c; + h *= FNV_PRIME; + } + return mix(h ^ length); + } + + public static long hashNumber(double value) { + double canonical = value == 0.0 ? 0.0 : value; + return mix(Double.doubleToLongBits(canonical) ^ NUMBER_SEED); + } + + private static long mix(long z) { + // SplitMix64 finalizer. + z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9L; + z = (z ^ (z >>> 27)) * 0x94d049bb133111ebL; + return z ^ (z >>> 31); + } + + /** Immutable snapshot of a checksum and its counts. */ + public record Result(long checksum, long[] counts) { + + public static Result of(SyntheaChecksum sum) { + return new Result(sum.checksum(), sum.counts()); + } + + public boolean sameAs(Result other) { + return checksum == other.checksum && Arrays.equals(counts, other.counts); + } + + public long resources() { + long total = 0; + for (long c : counts) { + total += c; + } + return total; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(String.format("checksum=%016x resources=%d", checksum, resources())); + for (int i = 0; i < counts.length; i++) { + sb.append(' ').append(TYPE_NAMES[i]).append('=').append(counts[i]); + } + return sb.toString(); + } + } +} diff --git a/src/jmh/java/org/simdjson/synthea/SyntheaCorpus.java b/src/jmh/java/org/simdjson/synthea/SyntheaCorpus.java new file mode 100644 index 0000000..f3274db --- /dev/null +++ b/src/jmh/java/org/simdjson/synthea/SyntheaCorpus.java @@ -0,0 +1,220 @@ +package org.simdjson.synthea; + +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.stream.Stream; + +/** + * A deterministic, in-memory selection of Synthea FHIR bundles. + *

+ * Configuration (system properties): + *

    + *
  • {@code synthea.dir} (required): directory searched recursively for {@code *.json} files.
  • + *
  • {@code synthea.maxFiles} (default 256): take at most this many files.
  • + *
  • {@code synthea.maxBytes} (default unlimited): stop before the first file that would push the + * selection over this many bytes.
  • + *
  • {@code synthea.expectFingerprint} (optional): fail if the selection's fingerprint differs.
  • + *
+ * Files are sorted by their path relative to {@code synthea.dir} ('/'-separated, {@link String#compareTo}), + * and the first ones are taken, so the same directory and limits always select the same files. + * Every document is stored in its own array with {@link #PADDING} zero bytes after the JSON, so the parser + * never has to copy it into its internal padded buffer. + */ +public final class SyntheaCorpus { + + public static final int PADDING = 64; + + private final Path root; + private final String[] names; + private final byte[][] documents; + private final int[] lengths; + private final long totalBytes; + private final int maxLength; + private final String largestName; + private final String fingerprint; + + private SyntheaCorpus(Path root, String[] names, byte[][] documents, int[] lengths) { + this.root = root; + this.names = names; + this.documents = documents; + this.lengths = lengths; + long total = 0; + int max = 0; + String largest = null; + for (int i = 0; i < lengths.length; i++) { + total += lengths[i]; + if (lengths[i] > max) { + max = lengths[i]; + largest = names[i]; + } + } + this.totalBytes = total; + this.maxLength = max; + this.largestName = largest; + this.fingerprint = computeFingerprint(names, lengths); + } + + public static SyntheaCorpus fromSystemProperties() { + String dir = System.getProperty("synthea.dir"); + if (dir == null || dir.isBlank()) { + throw new IllegalStateException("System property synthea.dir is not set. " + + "Point it at a directory containing Synthea FHIR bundles (*.json)."); + } + int maxFiles = Integer.parseInt(System.getProperty("synthea.maxFiles", "256")); + long maxBytes = Long.parseLong(System.getProperty("synthea.maxBytes", String.valueOf(Long.MAX_VALUE))); + SyntheaCorpus corpus = load(Paths.get(dir), maxFiles, maxBytes); + String expected = System.getProperty("synthea.expectFingerprint"); + if (expected != null && !expected.isBlank() && !expected.equals(corpus.fingerprint)) { + throw new IllegalStateException("Corpus fingerprint mismatch: expected " + expected + + " but the selected files have " + corpus.fingerprint); + } + return corpus; + } + + public static SyntheaCorpus load(Path root, int maxFiles, long maxBytes) { + if (maxFiles <= 0) { + throw new IllegalArgumentException("synthea.maxFiles must be positive, got " + maxFiles); + } + if (!Files.isDirectory(root)) { + throw new IllegalStateException("synthea.dir is not a directory: " + root.toAbsolutePath()); + } + List all = new ArrayList<>(); + try (Stream paths = Files.walk(root)) { + paths.filter(p -> p.getFileName().toString().endsWith(".json")) + .filter(Files::isRegularFile) + .forEach(p -> all.add(relativeName(root, p))); + } catch (IOException e) { + throw new UncheckedIOException("Cannot list " + root, e); + } + if (all.isEmpty()) { + throw new IllegalStateException("No *.json files found under " + root.toAbsolutePath()); + } + all.sort(String::compareTo); + + List names = new ArrayList<>(); + List documents = new ArrayList<>(); + List lengths = new ArrayList<>(); + long total = 0; + for (String name : all) { + if (names.size() == maxFiles) { + break; + } + Path path = root.resolve(name); + long size = size(path); + if (size > Integer.MAX_VALUE - PADDING) { + throw new IllegalStateException("File too large for a byte array: " + path); + } + if (total + size > maxBytes) { + break; + } + byte[] document = new byte[(int) size + PADDING]; + read(path, document, (int) size); + names.add(name); + documents.add(document); + lengths.add((int) size); + total += size; + } + if (names.isEmpty()) { + throw new IllegalStateException("synthea.maxBytes=" + maxBytes + " excludes even the first file " + all.get(0)); + } + int[] lengthArray = new int[lengths.size()]; + for (int i = 0; i < lengthArray.length; i++) { + lengthArray[i] = lengths.get(i); + } + return new SyntheaCorpus(root, names.toArray(new String[0]), documents.toArray(new byte[0][]), lengthArray); + } + + private static String relativeName(Path root, Path file) { + StringBuilder sb = new StringBuilder(); + for (Path part : root.relativize(file)) { + if (!sb.isEmpty()) { + sb.append('/'); + } + sb.append(part); + } + return sb.toString(); + } + + private static long size(Path path) { + try { + return Files.size(path); + } catch (IOException e) { + throw new UncheckedIOException("Cannot stat " + path, e); + } + } + + private static void read(Path path, byte[] target, int size) { + try (InputStream in = Files.newInputStream(path)) { + int n = in.readNBytes(target, 0, size); + if (n != size || in.read() != -1) { + throw new IllegalStateException("File changed while loading: " + path); + } + } catch (IOException e) { + throw new UncheckedIOException("Cannot read " + path, e); + } + } + + private static String computeFingerprint(String[] names, int[] lengths) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (int i = 0; i < names.length; i++) { + digest.update(names[i].getBytes(StandardCharsets.UTF_8)); + digest.update((byte) 0); + digest.update(Integer.toString(lengths[i]).getBytes(StandardCharsets.US_ASCII)); + digest.update((byte) '\n'); + } + return HexFormat.of().formatHex(digest.digest(), 0, 8); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + public void printSummary(PrintStream out) { + out.println("Synthea corpus: dir=" + root.toAbsolutePath() + + " files=" + size() + + " totalBytes=" + totalBytes + + " largest=" + maxLength + " (" + largestName + ")" + + " fingerprint=" + fingerprint); + } + + public int size() { + return documents.length; + } + + public String name(int i) { + return names[i]; + } + + /** The JSON bytes of document {@code i}, followed by at least {@link #PADDING} zero bytes. */ + public byte[] document(int i) { + return documents[i]; + } + + public int length(int i) { + return lengths[i]; + } + + public long totalBytes() { + return totalBytes; + } + + public int maxLength() { + return maxLength; + } + + /** First 16 hex digits of SHA-256 over the selected relative names and sizes, in selection order. */ + public String fingerprint() { + return fingerprint; + } +} diff --git a/src/jmh/java/org/simdjson/synthea/SyntheaExtractor.java b/src/jmh/java/org/simdjson/synthea/SyntheaExtractor.java new file mode 100644 index 0000000..55a902c --- /dev/null +++ b/src/jmh/java/org/simdjson/synthea/SyntheaExtractor.java @@ -0,0 +1,823 @@ +package org.simdjson.synthea; + +import org.simdjson.JsonValue; +import org.simdjson.OnDemandJsonIterator; +import org.simdjson.OnDemandJsonIterator.IteratorResult; +import org.simdjson.OnDemandJsonIterator.ValueType; +import org.simdjson.SimdJsonParser; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import static java.nio.charset.StandardCharsets.US_ASCII; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.simdjson.synthea.SyntheaChecksum.ABSENT; +import static org.simdjson.synthea.SyntheaChecksum.CONDITION; +import static org.simdjson.synthea.SyntheaChecksum.ENCOUNTER; +import static org.simdjson.synthea.SyntheaChecksum.OBSERVATION; +import static org.simdjson.synthea.SyntheaChecksum.OTHER; +import static org.simdjson.synthea.SyntheaChecksum.PATIENT; +import static org.simdjson.synthea.SyntheaChecksum.hashNumber; +import static org.simdjson.synthea.SyntheaChecksum.hashString; + +/** + * The extraction task, implemented once per parsing mode. Every mode must produce the same checksum and + * counts; {@link SyntheaBundleVerifier} checks this. + *

+ * For every {@code entry[i].resource} that is a JSON object, in document order, the following values are + * folded into the checksum, always in this order: + *

+ *   all resources : resourceType, id
+ *   Patient       : birthDate, gender
+ *   Encounter     : period.start, class.code
+ *   Observation   : code.coding[0].code, effectiveDateTime, valueQuantity.value (number), valueQuantity.unit
+ *   Condition     : code.coding[0].code, onsetDateTime
+ * 
+ * and the resource is counted under its type (anything else, including a missing resourceType, counts + * as "other"). Values are strings unless marked otherwise. A missing value, {@code null}, or a value of + * another JSON type folds {@link SyntheaChecksum#ABSENT}. If a key occurs more than once in an object the + * modes may disagree (JSON leaves this undefined); the verifier would report it. + *

+ * Not thread-safe: one instance per thread. + */ +public final class SyntheaExtractor { + + public enum Mode { + DOM_GET_STRING("domGetString") { + @Override + void run(SyntheaExtractor extractor, byte[] buffer, int length) { + extractor.domGetString(buffer, length); + } + }, + SCHEMA_BASED("schemaBased") { + @Override + void run(SyntheaExtractor extractor, byte[] buffer, int length) { + extractor.schemaBased(buffer, length); + } + }, + DOM_GET_BYTES("domGetBytes") { + @Override + void run(SyntheaExtractor extractor, byte[] buffer, int length) { + extractor.domGetBytes(buffer, length); + } + }, + DOM_INDEX("domIndex") { + @Override + void run(SyntheaExtractor extractor, byte[] buffer, int length) { + extractor.domIndex(buffer, length); + } + }, + ON_DEMAND("onDemand") { + @Override + void run(SyntheaExtractor extractor, byte[] buffer, int length) { + extractor.onDemand(buffer, length); + } + }; + + private final String label; + + Mode(String label) { + this.label = label; + } + + public String label() { + return label; + } + + abstract void run(SyntheaExtractor extractor, byte[] buffer, int length); + } + + /** System property selecting UTF-8 validation for every parser of the benchmark: true (default) or false. */ + public static final String VALIDATE_UTF8_PROPERTY = "synthea.validateUtf8"; + + private final SimdJsonParser parser; + private final SyntheaChecksum sum = new SyntheaChecksum(); + private final int maxDocumentLength; + + /** + * @param maxDocumentLength the length of the largest document this instance will parse + * @param validateUtf8 passed to {@link SimdJsonParser#SimdJsonParser(int, int, boolean)} + */ + public SyntheaExtractor(int maxDocumentLength, boolean validateUtf8) { + this.maxDocumentLength = maxDocumentLength; + parser = new SimdJsonParser(maxDocumentLength + SyntheaCorpus.PADDING, 1024, validateUtf8); + } + + /** Reads {@link #VALIDATE_UTF8_PROPERTY}; anything but "true" or "false" is rejected. */ + public static boolean validateUtf8FromSystemProperties() { + String value = System.getProperty(VALIDATE_UTF8_PROPERTY, "true"); + return switch (value) { + case "true" -> true; + case "false" -> false; + default -> throw new IllegalStateException("System property " + VALIDATE_UTF8_PROPERTY + + " must be true or false, but is '" + value + "'."); + }; + } + + public SimdJsonParser parser() { + return parser; + } + + public SyntheaChecksum sum() { + return sum; + } + + public void run(Mode mode, byte[] buffer, int length) { + mode.run(this, buffer, length); + } + + private static int typeOf(String resourceType) { + if (resourceType == null) { + return OTHER; + } + return switch (resourceType) { + case "Patient" -> PATIENT; + case "Encounter" -> ENCOUNTER; + case "Observation" -> OBSERVATION; + case "Condition" -> CONDITION; + default -> OTHER; + }; + } + + private static long hashNullableString(String value) { + return value == null ? ABSENT : hashString(value); + } + + // --------------------------------------------------------------------------------------------------- + // domGetString: DOM (tape) with JsonValue.get(String) and arrayIterator(). + // --------------------------------------------------------------------------------------------------- + + public void domGetString(byte[] buffer, int length) { + JsonValue bundle = parser.parse(buffer, length); + if (!bundle.isObject()) { + return; + } + JsonValue entries = bundle.get("entry"); + if (entries == null || !entries.isArray()) { + return; + } + Iterator it = entries.arrayIterator(); + while (it.hasNext()) { + JsonValue entry = it.next(); + if (!entry.isObject()) { + continue; + } + JsonValue resource = entry.get("resource"); + if (resource != null && resource.isObject()) { + resourceGetString(resource); + } + } + } + + private void resourceGetString(JsonValue resource) { + String resourceType = stringOrNull(resource.get("resourceType")); + int type = typeOf(resourceType); + sum.fold(hashNullableString(resourceType)); + sum.fold(stringHash(resource.get("id"))); + switch (type) { + case PATIENT -> { + sum.fold(stringHash(resource.get("birthDate"))); + sum.fold(stringHash(resource.get("gender"))); + } + case ENCOUNTER -> { + sum.fold(stringHash(member(resource.get("period"), "start"))); + sum.fold(stringHash(member(resource.get("class"), "code"))); + } + case OBSERVATION -> { + sum.fold(stringHash(firstCodingCode(resource.get("code")))); + sum.fold(stringHash(resource.get("effectiveDateTime"))); + JsonValue quantity = resource.get("valueQuantity"); + sum.fold(numberHash(member(quantity, "value"))); + sum.fold(stringHash(member(quantity, "unit"))); + } + case CONDITION -> { + sum.fold(stringHash(firstCodingCode(resource.get("code")))); + sum.fold(stringHash(resource.get("onsetDateTime"))); + } + default -> { + } + } + sum.count(type); + } + + private static JsonValue member(JsonValue object, String name) { + return object != null && object.isObject() ? object.get(name) : null; + } + + private static JsonValue firstCodingCode(JsonValue codeableConcept) { + JsonValue coding = member(codeableConcept, "coding"); + if (coding == null || !coding.isArray()) { + return null; + } + Iterator it = coding.arrayIterator(); + return it.hasNext() ? member(it.next(), "code") : null; + } + + private static String stringOrNull(JsonValue value) { + return value != null && value.isString() ? value.asString() : null; + } + + private static long stringHash(JsonValue value) { + return hashNullableString(stringOrNull(value)); + } + + private static long numberHash(JsonValue value) { + if (value == null) { + return ABSENT; + } + if (value.isLong()) { + return hashNumber(value.asLong()); + } + if (value.isDouble()) { + return hashNumber(value.asDouble()); + } + return ABSENT; + } + + // --------------------------------------------------------------------------------------------------- + // schemaBased: upstream's schema-based parsing into records (SyntheaSchema). + // --------------------------------------------------------------------------------------------------- + + public void schemaBased(byte[] buffer, int length) { + SyntheaSchema.Bundle bundle = parser.parse(buffer, length, SyntheaSchema.Bundle.class); + if (bundle == null || bundle.entry() == null) { + return; + } + for (SyntheaSchema.Entry entry : bundle.entry()) { + if (entry != null && entry.resource() != null) { + resourceSchema(entry.resource()); + } + } + } + + private void resourceSchema(SyntheaSchema.Resource resource) { + int type = typeOf(resource.resourceType()); + sum.fold(hashNullableString(resource.resourceType())); + sum.fold(hashNullableString(resource.id())); + switch (type) { + case PATIENT -> { + sum.fold(hashNullableString(resource.birthDate())); + sum.fold(hashNullableString(resource.gender())); + } + case ENCOUNTER -> { + SyntheaSchema.Period period = resource.period(); + SyntheaSchema.Coding encounterClass = resource.encounterClass(); + sum.fold(hashNullableString(period == null ? null : period.start())); + sum.fold(hashNullableString(encounterClass == null ? null : encounterClass.code())); + } + case OBSERVATION -> { + SyntheaSchema.Quantity quantity = resource.valueQuantity(); + sum.fold(hashNullableString(firstCodingCode(resource.code()))); + sum.fold(hashNullableString(resource.effectiveDateTime())); + sum.fold(quantity == null || quantity.value() == null ? ABSENT : hashNumber(quantity.value())); + sum.fold(hashNullableString(quantity == null ? null : quantity.unit())); + } + case CONDITION -> { + sum.fold(hashNullableString(firstCodingCode(resource.code()))); + sum.fold(hashNullableString(resource.onsetDateTime())); + } + default -> { + } + } + sum.count(type); + } + + private static String firstCodingCode(SyntheaSchema.CodeableConcept codeableConcept) { + if (codeableConcept == null) { + return null; + } + List coding = codeableConcept.coding(); + if (coding == null || coding.isEmpty() || coding.get(0) == null) { + return null; + } + return coding.get(0).code(); + } + + // --------------------------------------------------------------------------------------------------- + // Pre-encoded keys and type names shared by domGetBytes, domIndex and onDemand. + // --------------------------------------------------------------------------------------------------- + + private static final byte[] K_ENTRY = utf8("entry"); + private static final byte[] K_RESOURCE = utf8("resource"); + private static final byte[] K_RESOURCE_TYPE = utf8("resourceType"); + private static final byte[] K_ID = utf8("id"); + private static final byte[] K_BIRTH_DATE = utf8("birthDate"); + private static final byte[] K_GENDER = utf8("gender"); + private static final byte[] K_PERIOD = utf8("period"); + private static final byte[] K_START = utf8("start"); + private static final byte[] K_CLASS = utf8("class"); + private static final byte[] K_CODE = utf8("code"); + private static final byte[] K_CODING = utf8("coding"); + private static final byte[] K_EFFECTIVE_DATE_TIME = utf8("effectiveDateTime"); + private static final byte[] K_VALUE_QUANTITY = utf8("valueQuantity"); + private static final byte[] K_VALUE = utf8("value"); + private static final byte[] K_UNIT = utf8("unit"); + private static final byte[] K_ONSET_DATE_TIME = utf8("onsetDateTime"); + + private static final byte[] T_PATIENT = utf8("Patient"); + private static final byte[] T_ENCOUNTER = utf8("Encounter"); + private static final byte[] T_OBSERVATION = utf8("Observation"); + private static final byte[] T_CONDITION = utf8("Condition"); + + private static byte[] utf8(String s) { + return s.getBytes(UTF_8); + } + + // --------------------------------------------------------------------------------------------------- + // domGetBytes: as domGetString, but JsonValue.get(byte[]) with pre-encoded keys. Values are still + // read with asString(), so the difference to domGetString is only the key encoding. + // --------------------------------------------------------------------------------------------------- + + public void domGetBytes(byte[] buffer, int length) { + JsonValue bundle = parser.parse(buffer, length); + if (!bundle.isObject()) { + return; + } + JsonValue entries = bundle.get(K_ENTRY); + if (entries == null || !entries.isArray()) { + return; + } + Iterator it = entries.arrayIterator(); + while (it.hasNext()) { + JsonValue entry = it.next(); + if (!entry.isObject()) { + continue; + } + JsonValue resource = entry.get(K_RESOURCE); + if (resource != null && resource.isObject()) { + resourceGetBytes(resource); + } + } + } + + private void resourceGetBytes(JsonValue resource) { + String resourceType = stringOrNull(resource.get(K_RESOURCE_TYPE)); + int type = typeOf(resourceType); + sum.fold(hashNullableString(resourceType)); + sum.fold(stringHash(resource.get(K_ID))); + switch (type) { + case PATIENT -> { + sum.fold(stringHash(resource.get(K_BIRTH_DATE))); + sum.fold(stringHash(resource.get(K_GENDER))); + } + case ENCOUNTER -> { + sum.fold(stringHash(member(resource.get(K_PERIOD), K_START))); + sum.fold(stringHash(member(resource.get(K_CLASS), K_CODE))); + } + case OBSERVATION -> { + sum.fold(stringHash(firstCodingCodeBytes(resource.get(K_CODE)))); + sum.fold(stringHash(resource.get(K_EFFECTIVE_DATE_TIME))); + JsonValue quantity = resource.get(K_VALUE_QUANTITY); + sum.fold(numberHash(member(quantity, K_VALUE))); + sum.fold(stringHash(member(quantity, K_UNIT))); + } + case CONDITION -> { + sum.fold(stringHash(firstCodingCodeBytes(resource.get(K_CODE)))); + sum.fold(stringHash(resource.get(K_ONSET_DATE_TIME))); + } + default -> { + } + } + sum.count(type); + } + + private static JsonValue member(JsonValue object, byte[] name) { + return object != null && object.isObject() ? object.get(name) : null; + } + + private static JsonValue firstCodingCodeBytes(JsonValue codeableConcept) { + JsonValue coding = member(codeableConcept, K_CODING); + if (coding == null || !coding.isArray()) { + return null; + } + Iterator it = coding.arrayIterator(); + return it.hasNext() ? member(it.next(), K_CODE) : null; + } + + // --------------------------------------------------------------------------------------------------- + // domIndex: DOM (tape) walked with the index-based JsonValue methods; string values are hashed + // straight from the parser's string buffer, so no JsonValue, Iterator or String is allocated. + // Every position is type-tested (isObjectAt, isArrayAt, isStringAt, isLongAt, isDoubleAt) before + // it is read, so a value of an unexpected JSON type folds ABSENT, as in the other modes. + // --------------------------------------------------------------------------------------------------- + + public void domIndex(byte[] buffer, int length) { + JsonValue bundle = parser.parse(buffer, length); + if (!bundle.isObject()) { + return; + } + int entries = bundle.field(bundle.index(), K_ENTRY); + if (entries < 0 || !bundle.isArrayAt(entries)) { + return; + } + int end = bundle.scopeEnd(entries); + for (int entry = bundle.firstElement(entries); entry >= 0 && entry < end; entry = bundle.advance(entry)) { + if (!bundle.isObjectAt(entry)) { + continue; + } + int resource = bundle.field(entry, K_RESOURCE); + if (resource >= 0 && bundle.isObjectAt(resource)) { + resourceIndex(bundle, resource); + } + } + } + + private void resourceIndex(JsonValue doc, int resource) { + int resourceType = doc.field(resource, K_RESOURCE_TYPE); + int type = typeAt(doc, resourceType); + sum.fold(stringHashAt(doc, resourceType)); + sum.fold(stringHashAt(doc, doc.field(resource, K_ID))); + switch (type) { + case PATIENT -> { + sum.fold(stringHashAt(doc, doc.field(resource, K_BIRTH_DATE))); + sum.fold(stringHashAt(doc, doc.field(resource, K_GENDER))); + } + case ENCOUNTER -> { + sum.fold(stringHashAt(doc, memberAt(doc, doc.field(resource, K_PERIOD), K_START))); + sum.fold(stringHashAt(doc, memberAt(doc, doc.field(resource, K_CLASS), K_CODE))); + } + case OBSERVATION -> { + sum.fold(stringHashAt(doc, firstCodingCodeAt(doc, doc.field(resource, K_CODE)))); + sum.fold(stringHashAt(doc, doc.field(resource, K_EFFECTIVE_DATE_TIME))); + int quantity = doc.field(resource, K_VALUE_QUANTITY); + sum.fold(numberHashAt(doc, memberAt(doc, quantity, K_VALUE))); + sum.fold(stringHashAt(doc, memberAt(doc, quantity, K_UNIT))); + } + case CONDITION -> { + sum.fold(stringHashAt(doc, firstCodingCodeAt(doc, doc.field(resource, K_CODE)))); + sum.fold(stringHashAt(doc, doc.field(resource, K_ONSET_DATE_TIME))); + } + default -> { + } + } + sum.count(type); + } + + private static int typeAt(JsonValue doc, int idx) { + if (idx < 0) { + return OTHER; + } + // stringEquals() is false for non-strings. + if (doc.stringEquals(idx, T_PATIENT)) { + return PATIENT; + } + if (doc.stringEquals(idx, T_ENCOUNTER)) { + return ENCOUNTER; + } + if (doc.stringEquals(idx, T_OBSERVATION)) { + return OBSERVATION; + } + if (doc.stringEquals(idx, T_CONDITION)) { + return CONDITION; + } + return OTHER; + } + + private static int memberAt(JsonValue doc, int object, byte[] name) { + return object >= 0 && doc.isObjectAt(object) ? doc.field(object, name) : -1; + } + + private static int firstCodingCodeAt(JsonValue doc, int codeableConcept) { + int coding = memberAt(doc, codeableConcept, K_CODING); + if (coding < 0 || !doc.isArrayAt(coding)) { + return -1; + } + return memberAt(doc, doc.firstElement(coding), K_CODE); + } + + private static long stringHashAt(JsonValue doc, int idx) { + if (idx < 0 || !doc.isStringAt(idx)) { + return ABSENT; + } + return hashString(doc.stringBytes(), doc.byteOffset(idx), doc.byteLength(idx)); + } + + private static long numberHashAt(JsonValue doc, int idx) { + if (idx < 0) { + return ABSENT; + } + if (doc.isLongAt(idx)) { + return hashNumber(doc.longAt(idx)); + } + if (doc.isDoubleAt(idx)) { + return hashNumber(doc.doubleAt(idx)); + } + return ABSENT; + } + + // --------------------------------------------------------------------------------------------------- + // onDemand: stage 1 only, then a forward-only cursor (SimdJsonParser.parseOnDemand). Wanted values + // are decoded, everything else is skipped with skipChild(). Fields arrive in document order, so each + // resource's value hashes are captured first and folded in the fixed order at the end of the + // resource. Fields are only decoded once the resourceType says they are needed; fields that come + // before resourceType are captured for every type (Synthea writes resourceType first). + // + // The JSON type of a value is checked with peekType() before choosing the getter, so a value of an + // unexpected type is skipped and folds ABSENT instead of making the getter throw. + // + // Strings and keys are decoded into one scratch buffer of the largest document's length plus + // OnDemandJsonIterator.STRING_BUFFER_PADDING: no decoded string or number literal is longer than the + // document, and the padding is the room the string decoder may write past the decoded string. + // --------------------------------------------------------------------------------------------------- + + private static final int UNKNOWN = -1; + + private static final int C_BIRTH_DATE = 0; + private static final int C_GENDER = 1; + private static final int C_PERIOD_START = 2; + private static final int C_CLASS_CODE = 3; + private static final int C_CODE = 4; + private static final int C_EFFECTIVE_DATE_TIME = 5; + private static final int C_QUANTITY_VALUE = 6; + private static final int C_QUANTITY_UNIT = 7; + private static final int C_ONSET_DATE_TIME = 8; + + private final long[] captured = new long[9]; + private byte[] scratch; + + public void onDemand(byte[] buffer, int length) { + if (scratch == null) { + scratch = new byte[maxDocumentLength + OnDemandJsonIterator.STRING_BUFFER_PADDING]; + } + OnDemandJsonIterator it = parser.parseOnDemand(buffer, length); + if (it.peekType() != ValueType.OBJECT || it.startIteratingRootObject() != IteratorResult.NOT_EMPTY) { + return; + } + do { + int keyLength = it.getFieldName(scratch); + it.moveToFieldValue(); + if (keyEquals(keyLength, K_ENTRY) && it.peekType() == ValueType.ARRAY) { + onDemandEntries(it); + } else { + it.skipChild(); + } + } while (it.nextObjectField()); + } + + private void onDemandEntries(OnDemandJsonIterator it) { + if (it.startIteratingArray() != IteratorResult.NOT_EMPTY) { + return; + } + do { + if (it.peekType() == ValueType.OBJECT) { + onDemandEntry(it); + } else { + it.skipChild(); + } + } while (it.nextArrayElement()); + } + + private void onDemandEntry(OnDemandJsonIterator it) { + if (it.startIteratingObject() != IteratorResult.NOT_EMPTY) { + return; + } + do { + int keyLength = it.getFieldName(scratch); + it.moveToFieldValue(); + if (keyEquals(keyLength, K_RESOURCE) && it.peekType() == ValueType.OBJECT) { + onDemandResource(it); + } else { + it.skipChild(); + } + } while (it.nextObjectField()); + } + + private void onDemandResource(OnDemandJsonIterator it) { + Arrays.fill(captured, ABSENT); + long typeHash = ABSENT; + long idHash = ABSENT; + int type = UNKNOWN; + if (it.startIteratingObject() == IteratorResult.NOT_EMPTY) { + do { + int keyLength = it.getFieldName(scratch); + it.moveToFieldValue(); + if (keyEquals(keyLength, K_RESOURCE_TYPE)) { + if (it.peekType() == ValueType.STRING) { + int n = it.getString(scratch); + typeHash = hashString(scratch, 0, n); + type = typeOf(scratch, n); + } else { + it.skipChild(); + type = OTHER; + } + } else if (keyEquals(keyLength, K_ID)) { + idHash = onDemandString(it); + } else if (wanted(type, PATIENT) && keyEquals(keyLength, K_BIRTH_DATE)) { + captured[C_BIRTH_DATE] = onDemandString(it); + } else if (wanted(type, PATIENT) && keyEquals(keyLength, K_GENDER)) { + captured[C_GENDER] = onDemandString(it); + } else if (wanted(type, ENCOUNTER) && keyEquals(keyLength, K_PERIOD)) { + captured[C_PERIOD_START] = onDemandMemberString(it, K_START); + } else if (wanted(type, ENCOUNTER) && keyEquals(keyLength, K_CLASS)) { + captured[C_CLASS_CODE] = onDemandMemberString(it, K_CODE); + } else if ((wanted(type, OBSERVATION) || wanted(type, CONDITION)) && keyEquals(keyLength, K_CODE)) { + captured[C_CODE] = onDemandFirstCodingCode(it); + } else if (wanted(type, OBSERVATION) && keyEquals(keyLength, K_EFFECTIVE_DATE_TIME)) { + captured[C_EFFECTIVE_DATE_TIME] = onDemandString(it); + } else if (wanted(type, OBSERVATION) && keyEquals(keyLength, K_VALUE_QUANTITY)) { + onDemandQuantity(it); + } else if (wanted(type, CONDITION) && keyEquals(keyLength, K_ONSET_DATE_TIME)) { + captured[C_ONSET_DATE_TIME] = onDemandString(it); + } else { + it.skipChild(); + } + } while (it.nextObjectField()); + } + if (type == UNKNOWN) { + type = OTHER; + } + sum.fold(typeHash); + sum.fold(idHash); + switch (type) { + case PATIENT -> { + sum.fold(captured[C_BIRTH_DATE]); + sum.fold(captured[C_GENDER]); + } + case ENCOUNTER -> { + sum.fold(captured[C_PERIOD_START]); + sum.fold(captured[C_CLASS_CODE]); + } + case OBSERVATION -> { + sum.fold(captured[C_CODE]); + sum.fold(captured[C_EFFECTIVE_DATE_TIME]); + sum.fold(captured[C_QUANTITY_VALUE]); + sum.fold(captured[C_QUANTITY_UNIT]); + } + case CONDITION -> { + sum.fold(captured[C_CODE]); + sum.fold(captured[C_ONSET_DATE_TIME]); + } + default -> { + } + } + sum.count(type); + } + + private static boolean wanted(int type, int candidate) { + return type == UNKNOWN || type == candidate; + } + + private boolean keyEquals(int keyLength, byte[] expected) { + return Arrays.equals(scratch, 0, keyLength, expected, 0, expected.length); + } + + private static int typeOf(byte[] bytes, int length) { + if (Arrays.equals(bytes, 0, length, T_PATIENT, 0, T_PATIENT.length)) { + return PATIENT; + } + if (Arrays.equals(bytes, 0, length, T_ENCOUNTER, 0, T_ENCOUNTER.length)) { + return ENCOUNTER; + } + if (Arrays.equals(bytes, 0, length, T_OBSERVATION, 0, T_OBSERVATION.length)) { + return OBSERVATION; + } + if (Arrays.equals(bytes, 0, length, T_CONDITION, 0, T_CONDITION.length)) { + return CONDITION; + } + return OTHER; + } + + /** Cursor at a value: its string hash, or ABSENT (value skipped) if it is not a string. */ + private long onDemandString(OnDemandJsonIterator it) { + if (it.peekType() != ValueType.STRING) { + it.skipChild(); + return ABSENT; + } + int n = it.getString(scratch); + return hashString(scratch, 0, n); + } + + /** Cursor at a value: its number hash, or ABSENT (value skipped) if it is not a number. */ + private long onDemandNumber(OnDemandJsonIterator it) { + if (it.peekType() != ValueType.NUMBER) { + it.skipChild(); + return ABSENT; + } + int n = it.getRawNumber(scratch); + return hashNumber(parseNumber(scratch, n)); + } + + /** Cursor at a value: hash of string member {@code name} if the value is an object, else ABSENT. */ + private long onDemandMemberString(OnDemandJsonIterator it, byte[] name) { + if (it.peekType() != ValueType.OBJECT) { + it.skipChild(); + return ABSENT; + } + long hash = ABSENT; + if (it.startIteratingObject() != IteratorResult.NOT_EMPTY) { + return hash; + } + do { + int keyLength = it.getFieldName(scratch); + it.moveToFieldValue(); + if (keyEquals(keyLength, name)) { + hash = onDemandString(it); + } else { + it.skipChild(); + } + } while (it.nextObjectField()); + return hash; + } + + /** Cursor at a CodeableConcept value: hash of coding[0].code, or ABSENT. */ + private long onDemandFirstCodingCode(OnDemandJsonIterator it) { + if (it.peekType() != ValueType.OBJECT) { + it.skipChild(); + return ABSENT; + } + long hash = ABSENT; + if (it.startIteratingObject() != IteratorResult.NOT_EMPTY) { + return hash; + } + do { + int keyLength = it.getFieldName(scratch); + it.moveToFieldValue(); + if (keyEquals(keyLength, K_CODING) && it.peekType() == ValueType.ARRAY) { + if (it.startIteratingArray() == IteratorResult.NOT_EMPTY) { + boolean first = true; + do { + if (first) { + first = false; + hash = onDemandMemberString(it, K_CODE); + } else { + it.skipChild(); + } + } while (it.nextArrayElement()); + } + } else { + it.skipChild(); + } + } while (it.nextObjectField()); + return hash; + } + + /** Cursor at a valueQuantity value: captures value (number) and unit (string). */ + private void onDemandQuantity(OnDemandJsonIterator it) { + if (it.peekType() != ValueType.OBJECT) { + it.skipChild(); + return; + } + if (it.startIteratingObject() != IteratorResult.NOT_EMPTY) { + return; + } + do { + int keyLength = it.getFieldName(scratch); + it.moveToFieldValue(); + if (keyEquals(keyLength, K_VALUE)) { + captured[C_QUANTITY_VALUE] = onDemandNumber(it); + } else if (keyEquals(keyLength, K_UNIT)) { + captured[C_QUANTITY_UNIT] = onDemandString(it); + } else { + it.skipChild(); + } + } while (it.nextObjectField()); + } + + private static final double[] POWERS_OF_TEN = { + 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, + 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22 + }; + + /** + * Converts a JSON number literal (as copied by getRawNumber) to the nearest double, without + * allocating in the common case. With at most 15 significant digits, no exponent and at most 22 + * fraction digits, the digits form an exact double and so does 10^k, and one IEEE division rounds + * correctly (Clinger's fast path). Anything else goes through Double.parseDouble. + */ + static double parseNumber(byte[] raw, int length) { + int i = 0; + boolean negative = length > 0 && raw[0] == '-'; + if (negative) { + i++; + } + long digits = 0; + int significant = 0; + int fractionDigits = 0; + boolean inFraction = false; + for (; i < length; i++) { + byte b = raw[i]; + if (b >= '0' && b <= '9') { + digits = digits * 10 + (b - '0'); + if (digits != 0) { + significant++; + } + if (inFraction) { + fractionDigits++; + } + if (significant > 15) { + return Double.parseDouble(new String(raw, 0, length, US_ASCII)); + } + } else if (b == '.' && !inFraction) { + inFraction = true; + } else { + return Double.parseDouble(new String(raw, 0, length, US_ASCII)); + } + } + if (fractionDigits >= POWERS_OF_TEN.length) { + return Double.parseDouble(new String(raw, 0, length, US_ASCII)); + } + double value = (double) digits / POWERS_OF_TEN[fractionDigits]; + return negative ? -value : value; + } +} diff --git a/src/jmh/java/org/simdjson/synthea/SyntheaSchema.java b/src/jmh/java/org/simdjson/synthea/SyntheaSchema.java new file mode 100644 index 0000000..ffd67c2 --- /dev/null +++ b/src/jmh/java/org/simdjson/synthea/SyntheaSchema.java @@ -0,0 +1,49 @@ +package org.simdjson.synthea; + +import org.simdjson.annotations.JsonFieldName; + +import java.util.List; + +/** + * Records for schema-based parsing ({@code SimdJsonParser.parse(buffer, len, Bundle.class)}). + *

+ * Schema-based parsing maps one Java type per JSON field name, so {@link Resource} is the union of the + * fields the extraction needs from every resource type. Fields not declared here are skipped by the parser. + */ +final class SyntheaSchema { + + private SyntheaSchema() { + } + + record Bundle(List entry) { + } + + record Entry(Resource resource) { + } + + record Resource( + String resourceType, + String id, + String birthDate, + String gender, + Period period, + @JsonFieldName("class") Coding encounterClass, + CodeableConcept code, + String effectiveDateTime, + Quantity valueQuantity, + String onsetDateTime) { + } + + record Period(String start) { + } + + record Coding(String code) { + } + + record CodeableConcept(List coding) { + } + + // FHIR Quantity.value is a JSON number that Synthea writes both as integers ("2") and as decimals ("108.1"). + record Quantity(Double value, String unit) { + } +} From 6dcb6f5b7e4550882496d653312a8357fd5f1d00 Mon Sep 17 00:00:00 2001 From: Morris Meyer Date: Sat, 21 Nov 2026 20:40:08 +0000 Subject: [PATCH 8/9] Document on-demand parsing, index-based navigation and the UTF-8 option Add README sections with short examples for parseOnDemand, the index-based JsonValue methods and SimdJsonParser(capacity, maxDepth, validateUtf8), and describe how to run the Synthea benchmark and verifier against a locally generated corpus. --- README.md | 105 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) diff --git a/README.md b/README.md index 9843d48..d2b5064 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,83 @@ record SimdJsonTwitter(List statuses) { } ``` +### On-Demand Parser + +The on-demand parser builds no DOM. `parseOnDemand` indexes the document and returns a forward-only cursor that decodes +only the values you ask for and skips everything else with `skipChild()`. Strings and field names are decoded into your +own byte array, which needs `OnDemandJsonIterator.STRING_BUFFER_PADDING` spare bytes after the longest string you expect. + +```java +byte[] json = loadTwitterJson(); +byte[] statuses = "statuses".getBytes(UTF_8); +byte[] id = "id".getBytes(UTF_8); +byte[] name = new byte[64 + OnDemandJsonIterator.STRING_BUFFER_PADDING]; + +SimdJsonParser parser = new SimdJsonParser(); +OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); +if (it.startIteratingRootObject() == IteratorResult.NOT_EMPTY) { + do { + int nameLength = it.getFieldName(name); + it.moveToFieldValue(); + if (!Arrays.equals(name, 0, nameLength, statuses, 0, statuses.length)) { + it.skipChild(); + } else if (it.startIteratingArray() == IteratorResult.NOT_EMPTY) { + do { + if (it.startIteratingObject() == IteratorResult.NOT_EMPTY) { + do { + nameLength = it.getFieldName(name); + it.moveToFieldValue(); + if (Arrays.equals(name, 0, nameLength, id, 0, id.length)) { + System.out.println(it.getNonNullLong()); + } else { + it.skipChild(); + } + } while (it.nextObjectField()); + } + } while (it.nextArrayElement()); + } + } while (it.nextObjectField()); +} +``` + +`peekType()` tells you the JSON type of the next value before you pick a getter. The cursor belongs to its parser and is +valid until the parser's next parse call. See the javadoc of `OnDemandJsonIterator` for the details, including how to skip +the rest of an object or array from inside it. + +### Allocation-Free Navigation + +`JsonValue` can also be navigated with plain `int` indices, which avoids allocating a `JsonValue`, an iterator or a +`String` per value. Field names are passed as pre-encoded byte arrays, and strings can be read straight from the parser's +buffer with `stringBytes()`, `byteOffset(int)` and `byteLength(int)`. + +```java +JsonValue doc = parser.parse(json, json.length); +int tweets = doc.field(doc.index(), STATUSES); +if (tweets >= 0 && doc.isArrayAt(tweets)) { + int end = doc.scopeEnd(tweets); + for (int tweet = doc.firstElement(tweets); tweet >= 0 && tweet < end; tweet = doc.advance(tweet)) { + int id = doc.isObjectAt(tweet) ? doc.field(tweet, ID) : -1; + if (id >= 0 && doc.isLongAt(id)) { + System.out.println(doc.longAt(id)); + } + } +} +``` + +Methods that need a value of a particular type, such as `field` or `longAt`, throw an `IllegalArgumentException` for an +index of another type; the `is...At` methods test the type first. + +### Skipping UTF-8 Validation + +By default, every document is validated as UTF-8. If your input is already known to be valid, for example because a +trusted component produced or checked it, you can skip that step: + +```java +SimdJsonParser parser = new SimdJsonParser(capacity, maxDepth, false); +``` + +Invalid UTF-8 is then not detected, and strings decoded from it may be malformed. + ## Installation The library is available in the [Maven Central Repository](https://mvnrepository.com/artifact/org.simdjson/simdjson-java). @@ -81,6 +158,34 @@ To run the JMH benchmarks, execute the following command: ```./gradlew jmh``` +### Synthea FHIR Benchmark + +[SyntheaBundleBenchmark](src/jmh/java/org/simdjson/synthea/SyntheaBundleBenchmark.java) extracts a fixed set of fields +from [Synthea](https://github.com/synthetichealth/synthea) FHIR bundles with the DOM, index-based, on-demand and +schema-based APIs. No data is included: generate bundles with Synthea and point the benchmark at the output directory. +Build the benchmark jar first: + +```./gradlew clean jmhJar``` + +Check that all modes extract the same values (exit status 0 when they agree): + +``` +java --add-modules jdk.incubator.vector -Dsynthea.dir=/path/to/output/fhir \ + -cp build/libs/simdjson-java-*-jmh.jar org.simdjson.synthea.SyntheaBundleVerifier +``` + +Run the benchmark: + +``` +java -jar build/libs/simdjson-java-*-jmh.jar 'org.simdjson.synthea.SyntheaBundleBenchmark' \ + -jvmArgsPrepend '--add-modules=jdk.incubator.vector' \ + -jvmArgsAppend '-Xmx8g -Dsynthea.dir=/path/to/output/fhir' +``` + +Both take the same system properties: `synthea.dir` (required), `synthea.maxFiles` (default 256), `synthea.maxBytes`, +`synthea.expectFingerprint` and `synthea.validateUtf8` (default `true`). Files are selected in a fixed order, and the +printed fingerprint identifies the selection. + ## Tests To run the tests, execute the following command: From 2f90e932352b763be319f8811fe5b8eef2885c67 Mon Sep 17 00:00:00 2001 From: Morris Meyer Date: Sat, 21 Nov 2026 20:40:08 +0000 Subject: [PATCH 9/9] Fix skipping malformed values that start with a byte above 0x7E skipChild looked up the depth change of every skipped token in a 127-entry table indexed with the token's first byte as a signed byte. A skipped object or array containing a malformed value that starts with 0x7F or a non-ASCII byte, such as an unquoted letter with an accent or, with UTF-8 validation off, an invalid UTF-8 byte, made it throw ArrayIndexOutOfBoundsException. The table now has 256 entries and is indexed with the unsigned byte, so such values are skipped like any other malformed scalar inside a skipped value. --- .../org/simdjson/OnDemandJsonIterator.java | 4 +- .../ObjectSchemaBasedParsingTest.java | 15 ++++++ .../org/simdjson/OnDemandParsingTest.java | 47 +++++++++++++++++++ 3 files changed, 64 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/simdjson/OnDemandJsonIterator.java b/src/main/java/org/simdjson/OnDemandJsonIterator.java index 3c3b2b5..eead51e 100644 --- a/src/main/java/org/simdjson/OnDemandJsonIterator.java +++ b/src/main/java/org/simdjson/OnDemandJsonIterator.java @@ -83,7 +83,7 @@ public class OnDemandJsonIterator { public static final int STRING_BUFFER_PADDING = StringParser.MAX_BYTES_WRITTEN_PAST_STRING; private static final byte SPACE = 0x20; - private static final int[] SKIP_DEPTH_PER_CHARACTER = new int[127]; + private static final int[] SKIP_DEPTH_PER_CHARACTER = new int[256]; static { Arrays.fill(SKIP_DEPTH_PER_CHARACTER, 0); @@ -225,7 +225,7 @@ public void skipChild(int parentDepth) { idx = indexer.getAndAdvance(); character = buffer[idx]; - int delta = SKIP_DEPTH_PER_CHARACTER[character]; + int delta = SKIP_DEPTH_PER_CHARACTER[character & 0xFF]; depth += delta; if (delta < 0 && depth <= parentDepth) { assertNoMoreJsonValuesAfterRoot(); diff --git a/src/test/java/org/simdjson/ObjectSchemaBasedParsingTest.java b/src/test/java/org/simdjson/ObjectSchemaBasedParsingTest.java index 071c77d..52cddf5 100644 --- a/src/test/java/org/simdjson/ObjectSchemaBasedParsingTest.java +++ b/src/test/java/org/simdjson/ObjectSchemaBasedParsingTest.java @@ -656,6 +656,21 @@ public void issue50() { assertThat(object.ccc()).isEqualTo(3); } + @ParameterizedTest + @ValueSource(ints = {'x', 0x7F, 0xE9, 0x20AC}) + public void unknownFieldWithMalformedValueIsSkipped(int codePoint) { + // given + SimdJsonParser parser = new SimdJsonParser(); + String value = String.valueOf((char) codePoint); + byte[] json = toUtf8("{\"a\": [" + value + "], \"b\": {\"c\": " + value + "}, \"field\": \"x\"}"); + + // when + RecordWithStringField object = parser.parse(json, json.length, RecordWithStringField.class); + + // then + assertThat(object.field()).isEqualTo("x"); + } + private record Issue50(long aaa, long bbb, long ccc) { } diff --git a/src/test/java/org/simdjson/OnDemandParsingTest.java b/src/test/java/org/simdjson/OnDemandParsingTest.java index 08972dd..5fcd7d5 100644 --- a/src/test/java/org/simdjson/OnDemandParsingTest.java +++ b/src/test/java/org/simdjson/OnDemandParsingTest.java @@ -1140,6 +1140,53 @@ public void parserReuseAcrossEntryPoints() { assertThat(onDemandFirst).isEqualTo(domFirst); } + @ParameterizedTest + @ValueSource(ints = {'x', 0x7F, 0xE9, 0x20AC}) + public void skipChildOverMalformedValueStartingWithAnyCharacter(int codePoint) { + // given + SimdJsonParser parser = new SimdJsonParser(); + String value = String.valueOf((char) codePoint); + byte[] json = toUtf8("[[" + value + "], {\"a\": " + value + "}, " + value + ", 1]"); + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + + // when + it.skipChild(); + assertThat(it.nextArrayElement()).isTrue(); + it.skipChild(); + assertThat(it.nextArrayElement()).isTrue(); + JsonParsingException ex = assertThrows(JsonParsingException.class, it::peekType); + it.skipChild(); + assertThat(it.nextArrayElement()).isTrue(); + + // then + assertThat(ex).hasMessage("Unrecognized value starting at " + (json.length - 4 - toUtf8(value).length) + + ". Expected: object, array, string, number, 'true', 'false' or 'null'."); + assertThat(it.getNonNullLong()).isEqualTo(1); + assertThat(it.nextArrayElement()).isFalse(); + } + + @ParameterizedTest + @ValueSource(ints = {0x80, 0xC0, 0xFF}) + public void skipChildOverInvalidUtf8WithoutValidation(int invalidByte) { + // given + SimdJsonParser parser = new SimdJsonParser(1024, 64, false); + byte b = (byte) invalidByte; + byte[] json = {'[', '[', b, ']', ',', '{', '"', 'a', '"', ':', b, '}', ',', '1', ']'}; + OnDemandJsonIterator it = parser.parseOnDemand(json, json.length); + assertThat(it.startIteratingRootArray()).isEqualTo(IteratorResult.NOT_EMPTY); + + // when + it.skipChild(); + assertThat(it.nextArrayElement()).isTrue(); + it.skipChild(); + assertThat(it.nextArrayElement()).isTrue(); + + // then + assertThat(it.getNonNullLong()).isEqualTo(1); + assertThat(it.nextArrayElement()).isFalse(); + } + private String fieldName(OnDemandJsonIterator it) { int length = it.getFieldName(stringBuffer); return new String(stringBuffer, 0, length, UTF_8);