-
Notifications
You must be signed in to change notification settings - Fork 0
io_nats_jparse_source

The CharArrayOffsetCharSource class is a concrete implementation of the CharSource abstract class and the ParseConstants interface. It represents a character source backed by a character array, where the starting position of the character sequence is indicated by an offset. This class provides methods for parsing integer, long, float, and double values from the character sequence. It also includes a validation method to check if a substring represents a valid integer. Additionally, it implements an errorDetails method that generates a detailed error message based on the current character being processed and the current parsing state.
public static String debugCharDescription(int c) {
String charString;
if (c == ' ') {
charString = "[SPACE]";
} else if (c == '\t') {
charString = "[TAB]";
} else if (c == '\n') {
charString = "[NEWLINE]";
} else if (c == ETX) {
charString = "ETX";
} else {
charString = "'" + (char) c + "'";
}
charString = charString + " with an int value of " + c;
return charString;
}The debugCharDescription method in the CharArrayOffsetCharSource class is responsible for providing a textual description of a given character based on its ASCII value.
Here is the step-by-step description of what this method does:
- The method takes an integer value
cas input. - It initializes a variable called
charStringto hold the description of the character. - It checks if the input character
cis equal to a space character. If true, it setscharStringto the string "[SPACE]". - If the input character
cis a tab character, it setscharStringto the string "[TAB]". - If the input character
cis a newline character, it setscharStringto the string "[NEWLINE]". - If
cis equal to a special character identified asETX, it setscharStringto the string "ETX". - If the character
cdoes not match any of the above conditions, it appends the character tocharStringby converting the ASCII value ofcto a character using(char) c. For example, ifcis 65, the character 'A' will be appended as "'A'". - Finally, the method appends " with an int value of " and the value of
cto the current value ofcharString. - The method returns the final value of
charString, which represents the description of the character based on its ASCII value.
public int next()
@Override
public int next() {
if (index + 1 >= sourceEndIndex) {
index = sourceEndIndex;
return ETX;
}
return data[++index];
}This method is overridden from the parent class to provide the functionality of iterating over the characters in the underlying char array source.
- Check if the current index (
index) incremented by 1 is greater than or equal to the end index of the source array (sourceEndIndex).- If true, set
indextosourceEndIndexand return theETXconstant, which indicates the end of the stream.
- If true, set
- Otherwise, increment
indexby 1 and return the character at the updated index in thedataarray.
Note: The data array is the char array source, and index is a variable that keeps track of the current position in the array. The ETX constant represents the end of the stream.

public int findAttributeEnd()
@Override
public int findAttributeEnd() {
int index = this.index;
final char[] data = this.data;
final int end = this.sourceEndIndex;
loop: for (; index < end; index++) {
char ch = data[index];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
case ATTRIBUTE_SEP:
this.index = index;
break loop;
}
}
return index;
}The findAttributeEnd method is defined in the CharArrayOffsetCharSource class and is used to find the end index of an attribute. Here is a step-by-step description of how the method works:
-
The method overrides the
findAttributeEndmethod defined in the parent class. -
It initializes the local variable
indexwith the value of the instance variablethis.index. This variable represents the current index position in the character array. -
It creates a local variable
dataand assigns it the value of the instance variablethis.data. This variable represents the character array from which the attribute is being extracted. -
It creates a local variable
endand assigns it the value of the instance variablethis.sourceEndIndex. This variable represents the end index of the character array. -
It enters a loop that iterates from the current index position (
index) to the end index (end) of the character array. -
Within each iteration of the loop, it retrieves the character at the current index position (
index) from the character array and assigns it to the variablech. -
It checks the value of
chusing a switch statement. -
If
chmatches any of the case valuesNEW_LINE_WS,CARRIAGE_RETURN_WS,TAB_WS,SPACE_WS, orATTRIBUTE_SEP, it updates the instance variablethis.indexwith the value ofindexand breaks out of the loop labeledloop. -
After the loop ends, it returns the value of index, which represents the end index of the attribute.
In summary, the findAttributeEnd method iterates through a character array starting from the current index position and looks for specific characters that indicate the end of an attribute. Once a matching character is found, it updates the instance variable this.index and returns the end index.

public boolean findChar(char c)
@Override
public boolean findChar(char c) {
int index = this.index;
final char[] data = this.data;
final int end = sourceEndIndex;
for (; index < end; index++) {
if (data[index] == c) {
this.index = index;
return true;
}
}
return false;
}The findChar method is used to search for a specific character within a character array. Here is a step-by-step description of what the method does:
- The method receives a character
cas a parameter. - It assigns the current index of the CharArrayOffsetCharSource object to the local variable
index. - It retrieves the character array
datafrom the CharArrayOffsetCharSource object. - It retrieves the end index of the source from the CharArrayOffsetCharSource object and assigns it to the local variable
end. - It starts a loop that iterates from the current index
indexuntil the end indexend. - Within each iteration, it checks if the character at position
indexwithin thedataarray is equal to the characterc. - If a match is found, it updates the current index of the CharArrayOffsetCharSource object to the value of
indexand returnstrue. - If no match is found after iterating through the entire array, it simply returns
false. - The method is marked as
@Override, indicating that it overrides a method from a superclass or interface.
Overall, the findChar method performs a linear search for a specific character c within the character array data. It updates the current index of the CharArrayOffsetCharSource object if a match is found and returns true. Otherwise, it returns false indicating that the character was not found.

public void checkForJunk()
@Override
public void checkForJunk() {
int index = this.index;
final char[] data = this.data;
final int end = this.sourceEndIndex;
int ch = ETX;
for (; index < end; index++) {
ch = data[index];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
continue;
default:
throw new UnexpectedCharacterException("Junk", "Unexpected extra characters", this);
}
}
}The checkForJunk method, defined in the io.nats.jparse.source.CharArrayOffsetCharSource class, is used to check for any junk characters in the provided character array.
Here is a step-by-step description of what the method does:
-
It starts by initializing variables:
indexwith the current index position in the character array,datawith the provided character array,endwith the end index of the character array, andchwith the ASCII value of ETX (End-of-Text). -
It enters a for loop that iterates from the current
indexto theendindex of the character array. -
Inside the loop, it assigns the value of
data[index]toch, which represents the current character being checked. -
It uses a switch statement to check the value of
chagainst predefined cases. The cases being checked are:a)
NEW_LINE_WS: Represents a new line whitespace character. b)CARRIAGE_RETURN_WS: Represents a carriage return whitespace character. c)TAB_WS: Represents a tab whitespace character. d)SPACE_WS: Represents a space whitespace character.If
chmatches any of the above cases, the loop continues to the next iteration without executing any further code. This means that if the current character is a whitespace character, it is considered valid and not classified as junk. -
If the value of
chdoes not match any of the cases above, it means that an unexpected character (considered as junk) has been encountered in the character array. In this case, anUnexpectedCharacterExceptionis thrown with the message "Junk" and "Unexpected extra characters". Thethisreference, representing the current instance of theCharArrayOffsetCharSourceclass, is passed as an argument to the exception. -
The for loop continues to the next iteration, and steps 3-5 are repeated until all characters in the character array have been checked.
By the end of the method, if no UnexpectedCharacterException is thrown, it means that there are no junk characters found in the provided character array.

public int nextSkipWhiteSpace()
@Override
public int nextSkipWhiteSpace() {
int index = this.index + 1;
final char[] data = this.data;
final int endIndex = sourceEndIndex;
int ch = ETX;
loop: for (; index < endIndex; index++) {
ch = data[index];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
continue;
default:
break loop;
}
}
this.index = index;
return index == endIndex ? ETX : ch;
}The nextSkipWhiteSpace method is defined in the CharArrayOffsetCharSource class in the io.nats.jparse.source package.
This method is used to skip white space characters in the data array starting from the current index. It returns the index of the next non-white space character, or ETX (end of text) if there are no more characters.
Here is a step-by-step description of what the method does:
- Increment
indexby 1 to start from the next character. - Store the reference to the
dataarray in a local variable nameddata. - Store the value of
sourceEndIndexin a local variable namedendIndex. - Create a variable
chand initialize it with theETXvalue. - Start a loop that will iterate from the current
indexuntil theendIndex. - Inside the loop, assign the character at
data[index]toch. - Use a switch statement to check the value of
ch.- If
chis equal toNEW_LINE_WSorCARRIAGE_RETURN_WSorTAB_WSorSPACE_WS, continue to the next iteration of the loop. - Otherwise, break out of the loop.
- If
- Update the
indexwith the value ofindex. - Return
ETXif theindexis equal toendIndex, otherwise return the value ofch.
This method effectively skips any white space characters (including new lines, carriage returns, tabs, and spaces) in the data array until a non-white space character is encountered. It then returns the index of that non-white space character. If there are no more characters after skipping white space, it returns the ETX value.

public char skipWhiteSpace()
@Override
public char skipWhiteSpace() {
int index = this.index;
final char[] data = this.data;
final int endIndex = sourceEndIndex;
char ch;
loop: for (; index < endIndex; index++) {
ch = data[index];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
continue;
default:
break loop;
}
}
this.index = index;
return data[index];
}The skipWhiteSpace method in the CharArrayOffsetCharSource class is used to skip any white space characters (spaces, tabs, new lines, and carriage returns) in the character array.
Here is a step-by-step description of what the method is doing:
- It first initializes a local variable
indexwith the current value ofthis.index, which represents the current position in the character array. - It also initializes a local variable
datawith the reference to the character arraythis.datathat contains the source data. - It gets the
endIndexfrom thesourceEndIndexinstance variable, which represents the end position in the character array. - It declares a variable
chto store the current character being examined. - It enters a loop that iterates over the character array starting from the current
indextill theendIndex. - Inside the loop, it checks the character at the current index
data[index]against a set of white space characters:NEW_LINE_WS,CARRIAGE_RETURN_WS,TAB_WS, andSPACE_WS. - If the character matches any of the white space characters, the loop continues to the next iteration without performing any action.
- If the character does not match any of the white space characters, it breaks out of the loop using the
break loop;statement. - After the loop completes, it updates the
indexinstance variable with the currentindexvalue, representing the new position after skipping white space. - Finally, it returns the character at that position
data[index]from the character array.
So, the skipWhiteSpace method essentially advances the position in the character array to the next non-white space character and returns that character.

public String toEncodedStringIfNeeded(int startIndex, int endIndex)
@Override
public String toEncodedStringIfNeeded(int startIndex, int endIndex) {
final int start = startIndex + sourceStartIndex;
final int end = endIndex + sourceStartIndex;
if (CharArrayUtils.hasEscapeChar(data, start, end)) {
return getEncodedString(startIndex, endIndex);
} else {
return this.getString(startIndex, endIndex);
}
}The toEncodedStringIfNeeded method in the io.nats.jparse.source.CharArrayOffsetCharSource class is used to convert a portion of a character array into a string representation if it contains escape characters.
Here is a step-by-step description of what the method does:
-
The method overrides the
toEncodedStringIfNeededmethod from the ancestor class. -
The method takes two parameters -
startIndexandendIndex, which denote the range of characters to be converted to a string. -
It calculates the actual start index and end index within the
datacharacter array by adding thestartIndexandendIndexto thesourceStartIndexinstance variable. -
It checks if the portion of the character array from the calculated start index to end index (inclusive) contains any escape characters using the
CharArrayUtils.hasEscapeCharmethod. -
If the portion contains escape characters, it calls the
getEncodedStringmethod with thestartIndexandendIndexparameters to obtain the encoded string representation. -
If the portion does not contain any escape characters, it calls the
getStringmethod with thestartIndexandendIndexparameters to obtain the regular string representation. -
Finally, it returns the obtained string representation either with escape characters encoded or without any encoding based on the presence of escape characters within the portion of the character array specified by the
startIndexandendIndex.
public NumberParseResult findEndOfNumberFast()
@Override
public NumberParseResult findEndOfNumberFast() {
int i = index + 1;
char ch = 0;
final char[] data = this.data;
final int endIndex = this.sourceEndIndex;
for (; i < endIndex; i++) {
ch = data[i];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
case ATTRIBUTE_SEP:
case ARRAY_SEP:
case OBJECT_END_TOKEN:
case ARRAY_END_TOKEN:
index = i;
return new NumberParseResult(i - sourceStartIndex, false);
case NUM_0:
case NUM_1:
case NUM_2:
case NUM_3:
case NUM_4:
case NUM_5:
case NUM_6:
case NUM_7:
case NUM_8:
case NUM_9:
break;
case DECIMAL_POINT:
index = i;
return findEndOfFloatFast();
case EXPONENT_MARKER:
case EXPONENT_MARKER2:
index = i;
return parseFloatWithExponentFast();
default:
throw new IllegalStateException("Unexpected character " + ch + " at index " + index);
}
}
index = i;
return new NumberParseResult(i - sourceStartIndex, false);
}The method findEndOfNumberFast in the class io.nats.jparse.source.CharArrayOffsetCharSource is used to find the end position of a number within a character array.
Here is a step-by-step breakdown of what this method does:
-
It initializes the local variable
ito the value ofindex + 1. -
It initializes the local variable
chto 0. -
It assigns the value of
data(a char array) to the local variabledata. -
It assigns the value of
sourceEndIndex(the end index of the source) to the local variableendIndex. -
It starts a loop from
iuntil it reachesendIndex. -
Inside the loop, it retrieves the character at index
ifrom thedataarray and assigns it toch. -
It uses a switch statement to handle different cases based on the value of
ch.-
If
chmatches any of the specified cases (NEW_LINE_WS, CARRIAGE_RETURN_WS, TAB_WS, SPACE_WS, ATTRIBUTE_SEP, ARRAY_SEP, OBJECT_END_TOKEN, ARRAY_END_TOKEN), it updates the value ofindextoiand returns a newNumberParseResultobject with the length of the number (i - sourceStartIndex) and a boolean indicating that the number does not have a decimal point or exponent. -
If
chmatches any digit character (NUM_0, NUM_1, NUM_2, ..., NUM_9), it continues to the next iteration of the loop. -
If
chmatches the decimal point character (DECIMAL_POINT), it updates the value ofindextoiand calls thefindEndOfFloatFastmethod to find the end of a floating-point number. -
If
chmatches the exponent marker characters (EXPONENT_MARKER, EXPONENT_MARKER2), it updates the value ofindextoiand calls theparseFloatWithExponentFastmethod to parse the number with exponent notation. -
If none of the above cases match, it throws an
IllegalStateExceptionwith an error message indicating the unexpected character and its index.
-
-
After the loop ends, it updates the value of
indextoi. -
It returns a new
NumberParseResultobject with the length of the number (i - sourceStartIndex) and a boolean indicating that the number does not have a decimal point or exponent.
private NumberParseResult findEndOfFloatFast() {
int i = index + 1;
char ch = 0;
final char[] data = this.data;
final int endIndex = this.sourceEndIndex;
for (; i < endIndex; i++) {
ch = data[i];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
case ATTRIBUTE_SEP:
case ARRAY_SEP:
case OBJECT_END_TOKEN:
case ARRAY_END_TOKEN:
index = i;
return new NumberParseResult(i - sourceStartIndex, true);
case NUM_0:
case NUM_1:
case NUM_2:
case NUM_3:
case NUM_4:
case NUM_5:
case NUM_6:
case NUM_7:
case NUM_8:
case NUM_9:
break;
case EXPONENT_MARKER:
case EXPONENT_MARKER2:
index = i;
return parseFloatWithExponentFast();
default:
throw new UnexpectedCharacterException("Parsing JSON Float Number", "Unexpected character", this, ch, i);
}
}
index = i;
return new NumberParseResult(i - sourceStartIndex, true);
}The findEndOfFloatFast method in the io.nats.jparse.source.CharArrayOffsetCharSource class is responsible for finding the end of a float number in a JSON source.
Here is a step-by-step description of what the method does:
- Initialize the variable
iwith the value ofindex + 1. This indicates the starting index of the float number. - Initialize the variable
chwith the value0. - Get a reference to the
dataarray and store it in a local variable. - Get the
endIndexof the source and store it in a local variable. - Start a loop from
itoendIndex. - Get the character at index
ifrom thedataarray and store it in the variablech. - Switch on the value of
chto perform different actions based on its type.- If
chis a white space character (e.g.,NEW_LINE_WS,CARRIAGE_RETURN_WS,TAB_WS,SPACE_WS), comma (ATTRIBUTE_SEP), curly brace (OBJECT_END_TOKEN), or square bracket (ARRAY_END_TOKEN), set theindextoiand return aNumberParseResultobject indicating the number of characters parsed and that parsing is successful. - If
chis a digit character (NUM_0,NUM_1,NUM_2, ...,NUM_9), continue with the loop to parse the next character. - If
chis an exponent marker character (EXPONENT_MARKER,EXPONENT_MARKER2), set theindextoiand call theparseFloatWithExponentFast()method to parse the number with exponent notation. - If
chis any other character, throw anUnexpectedCharacterExceptionindicating that an unexpected character is encountered while parsing a JSON float number.
- If
- After the loop completes, set the
indextoito indicate the end index of the float number. - Return a
NumberParseResultobject indicating the number of characters parsed and a flag indicating a successful parse.
Note: The specific values (e.g., NEW_LINE_WS, CARRIAGE_RETURN_WS, TAB_WS, etc.) mentioned in the switch cases are assumed to be constants defined elsewhere in the code.

private NumberParseResult parseFloatWithExponentFast() {
int i = index + 1;
char ch = 0;
int signOperator = 0;
final char[] data = this.data;
final int end = sourceEndIndex;
for (; i < end; i++) {
ch = data[i];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
case ATTRIBUTE_SEP:
case ARRAY_SEP:
case OBJECT_END_TOKEN:
case ARRAY_END_TOKEN:
index = i;
return new NumberParseResult(i - sourceStartIndex, true);
case MINUS:
case PLUS:
signOperator++;
if (signOperator > 1) {
throw new IllegalStateException("Too many sign operators when parsing exponent of float");
}
break;
case NUM_0:
case NUM_1:
case NUM_2:
case NUM_3:
case NUM_4:
case NUM_5:
case NUM_6:
case NUM_7:
case NUM_8:
case NUM_9:
break;
default:
throw new IllegalStateException("Unexpected character " + ch + " at index " + index);
}
}
index = i;
return new NumberParseResult(i - sourceStartIndex, true);
}This method is defined in the io.nats.jparse.source.CharArrayOffsetCharSource class.
- Initialize a variable
iwith the value ofindex + 1. - Initialize a variable
chwith a value of 0. - Initialize a variable
signOperatorwith a value of 0. - Get the character array
datafrom the instance ofCharArrayOffsetCharSource. - Get the end index
endof the character source. - Enter a loop starting from
iuntilend. - Get the character at index
ifrom thedataarray and assign it toch. - Enter a switch statement based on the value of
ch:- If
chmatches any of the following cases:-
NEW_LINE_WS,CARRIAGE_RETURN_WS,TAB_WS,SPACE_WS,ATTRIBUTE_SEP,ARRAY_SEP,OBJECT_END_TOKEN, orARRAY_END_TOKEN, - Update the
indexvariable toiand return a newNumberParseResultobject with the differencei - sourceStartIndexand a value oftrue.
-
- If
chmatches eitherMINUSorPLUS,- Increment the
signOperatorvariable by 1. - If
signOperatoris greater than 1, throw anIllegalStateExceptionwith the message "Too many sign operators when parsing exponent of float".
- Increment the
- If
chmatches any of the following cases:-
NUM_0,NUM_1,NUM_2,NUM_3,NUM_4,NUM_5,NUM_6,NUM_7,NUM_8, orNUM_9, - Continue to the next iteration of the loop.
-
- If
chdoes not match any of the above cases, throw anIllegalStateExceptionwith the message "Unexpected characterchat indexindex".
- If
- After the loop, update the
indexvariable toi. - Return a new
NumberParseResultobject with the differencei - sourceStartIndexand a value oftrue.
public int findEndOfEncodedStringFast()
@Override
public int findEndOfEncodedStringFast() {
int i = ++index;
final char[] data = this.data;
final int end = sourceEndIndex;
boolean controlChar = false;
for (; i < end; i++) {
char ch = data[i];
switch(ch) {
case CONTROL_ESCAPE_TOKEN:
controlChar = !controlChar;
continue;
case STRING_END_TOKEN:
if (!controlChar) {
index = i + 1;
return i;
}
controlChar = false;
break;
default:
controlChar = false;
break;
}
}
throw new IllegalStateException("Unable to find closing for String");
}The findEndOfEncodedStringFast() method, defined in the io.nats.jparse.source.CharArrayOffsetCharSource class, is used to find the closing position of an encoded string within a character array.
Here is a step-by-step description of how the method works:
-
The method starts by incrementing the
indexvariable by 1 and assigning its value toi. -
It then retrieves the character array (
data) and the end index (end) from the source. -
The method initializes a boolean variable
controlCharto false. This variable keeps track of whether a control character (such as an escape character) has been encountered. -
A for loop is initiated, iterating through each character in the character array, starting from index
iand going up toend. -
Within the loop, the current character (
ch) is retrieved. -
A switch statement is used to check the value of the current character:
a. If the character is equal to
CONTROL_ESCAPE_TOKEN, thecontrolCharvariable is toggled (flipped) by assigning it the opposite value (true becomes false, false becomes true), and the loop continues to the next iteration.b. If the character is equal to
STRING_END_TOKEN, andcontrolCharis false (indicating that it's not within a control sequence), then the method updates theindexvariable to be equal toi + 1, and returns the current value ofi. This signifies that the closing position of the encoded string has been found.c. If the character does not match either of the above cases, the
controlCharvariable is set to false, indicating that it is not within a control sequence. -
If none of the characters within the loop match the conditions to find the closing position of the encoded string, the method throws an
IllegalStateExceptionwith a message stating "Unable to find closing for String". This serves as an indication that the closing position could not be found.
In summary, the findEndOfEncodedStringFast() method iterates through a character array, checking each character to determine the closing position of an encoded string. It considers control characters and checks for the end token to determine when the closing position is reached.

private int findEndOfStringControlEncode(int i) {
final char[] data = this.data;
final int length = data.length;
char ch = 0;
ch = data[i];
switch(ch) {
case CONTROL_ESCAPE_TOKEN:
case STRING_END_TOKEN:
case 'n':
case 'b':
case '/':
case 'r':
case 't':
case 'f':
return i;
case 'u':
return findEndOfHexEncoding(i);
default:
throw new UnexpectedCharacterException("Parsing JSON String", "Unexpected character while finding closing for String", this, ch, i);
}
}The findEndOfStringControlEncode method is defined in the io.nats.jparse.source.CharArrayOffsetCharSource class and takes an integer i as input. Below is a step-by-step description of what the method is doing:
- The method begins by declaring a local variable
data, which is assigned the value ofthis.data.this.datarefers to a char array that represents the source data being processed. - A local variable
lengthis declared and assigned the length of thedataarray. - A local variable
chof typecharis declared and initialized to 0. - The character at index
iof thedataarray is assigned toch. - A
switchstatement is used to perform different actions based on the value ofch.- If
chis equal toCONTROL_ESCAPE_TOKEN,STRING_END_TOKEN,'n','b','/','r','t', or'f', the method simply returnsi. These characters represent the control escape token and various escape sequences commonly found in JSON strings. - If
chis equal to'u', the method calls thefindEndOfHexEncodingmethod withias an argument and returns the result. This suggests thatfindEndOfHexEncodingis responsible for finding the end of a hexadecimal encoding, which is likely used to decode Unicode characters in the JSON string. - If none of the above cases match, it means that an unexpected character was encountered while trying to find the closing for a string. In this case, an
UnexpectedCharacterExceptionis thrown with a descriptive error message, including the current source (this), the unexpected characterch, and the current indexi.
- If
That concludes the step-by-step description of the findEndOfStringControlEncode method.

public int findEndOfEncodedString()
@Override
public int findEndOfEncodedString() {
int i = ++index;
final char[] data = this.data;
final int length = data.length;
char ch = 0;
for (; i < length; i++) {
ch = data[i];
switch(ch) {
case CONTROL_ESCAPE_TOKEN:
i = findEndOfStringControlEncode(i + 1);
continue;
case STRING_END_TOKEN:
index = i + 1;
return i;
default:
if (ch >= SPACE_WS) {
continue;
}
throw new UnexpectedCharacterException("Parsing JSON String", "Unexpected character while finding closing for String", this, ch, i);
}
}
throw new UnexpectedCharacterException("Parsing JSON Encoded String", "Unable to find closing for String", this, ch, i);
}The findEndOfEncodedString method is defined in the CharArrayOffsetCharSource class in the io.nats.jparse.source package. Here is a step-by-step description of what this method does:
- Declare a local variable
iand initialize it with the value of++index. This increments the value of theindexvariable by 1 and assigns the updated value toi. - Retrieve the
dataarray fromthisobject. This is the character array that the method operates on. - Get the length of the
dataarray and store it in thelengthvariable. - Declare a variable
chand initialize it with 0. - Start a loop that iterates through the array from the current value of
ito the end of the array (length). - Get the character at the current index
ifrom thedataarray and assign it toch. - Use a switch statement to perform different actions based on the value of
ch:- If
chis equal to theCONTROL_ESCAPE_TOKENconstant, call thefindEndOfStringControlEncodemethod with the argumenti + 1and assign its return value toi. This method is not provided, so we can't describe its exact behavior. - If
chis equal to theSTRING_END_TOKENconstant, update the value of theindexvariable toi + 1and return the current value ofi. - If none of the above conditions are true, check if
chis greater than or equal to theSPACE_WSconstant. If it is, continue to the next iteration of the loop. - If none of the conditions above are true, throw an
UnexpectedCharacterExceptionwith a message indicating that an unexpected character was encountered while finding the closing of a string. The exception includes information about the currentCharSource, the unexpected characterch, and its positioni.
- If
- If the loop completes without finding the closing of the string, throw an
UnexpectedCharacterExceptionwith a message indicating that the closing for the string could not be found. The exception includes information about the currentCharSource, the last characterchencountered, and its positioni.
private int findEndOfHexEncoding(int index) {
final char[] data = this.data;
final int length = data.length;
if (isHex(data[++index]) && isHex(data[++index]) && isHex(data[++index]) && isHex(data[++index])) {
return index;
} else {
throw new UnexpectedCharacterException("Parsing hex encoding in a string", "Unexpected character", this);
}
}The method findEndOfHexEncoding is defined in the class io.nats.jparse.source.CharArrayOffsetCharSource. It takes an index as a parameter and returns an integer.
Here is a step-by-step description of what the method does:
-
The method starts by getting the
dataarray and its length from the current instance ofCharArrayOffsetCharSource. -
It then checks if the character at the next index in the
dataarray is a valid hexadecimal character (isHex). It does this repeatedly for the next 4 characters by incrementing theindexfor each check. -
If all 4 characters are valid hexadecimal characters, the method returns the current value of
index. -
If any of the characters are not valid hexadecimal characters, the method throws an
UnexpectedCharacterException. The exception message states that it occurred while parsing a hex encoding in a string, and the unexpected character is included in the message. Thethisreference is passed as an argument to provide additional context.
In summary, the findEndOfHexEncoding method scans the data array starting from the given index and checks if the next 4 characters form a valid hex encoding. If they do, it returns the index. If not, it throws an exception.

private boolean isHex(char datum) {
switch(datum) {
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return true;
default:
return false;
}
}The isHex method in the io.nats.jparse.source.CharArrayOffsetCharSource class is used to determine whether a given character is a hexadecimal digit. Here is a step-by-step description of what the method does:
-
The method takes a single parameter
datum, which represents the character to be tested. -
The method uses a
switchstatement to check the value of thedatumcharacter. -
If the
datumcharacter is any of the following characters: 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', or '9', then the method returnstrue. These characters represent valid hexadecimal digits. -
If the
datumcharacter is not one of the specified hexadecimal digits, thedefaultcase is executed, and the method returnsfalse. -
So overall, the
isHexmethod determines whether a character is a hexadecimal digit by checking if it falls within the specified range of valid hexadecimal characters. If the character is within the range, the method returnstrue; otherwise, it returnsfalse.
public int findEndString()
@Override
public int findEndString() {
int i = ++index;
final char[] data = this.data;
final int length = data.length;
char ch = 0;
for (; i < length; i++) {
ch = data[i];
switch(ch) {
case STRING_END_TOKEN:
index = i;
return i;
default:
if (ch >= SPACE_WS) {
continue;
}
throw new UnexpectedCharacterException("Parsing JSON String", "Unexpected character while finding closing for String", this, ch, i);
}
}
throw new UnexpectedCharacterException("Parsing JSON String", "Unable to find closing for String", this, ch, i);
}This findEndString method is defined in the CharArrayOffsetCharSource class and it overrides the same method from the superclass.
Here is a step-by-step description of what this method does:
- It starts by incrementing the
indexvariable. - It retrieves the
dataarray and its length from the class instance. - It declares a
chvariable and sets it to 0. - It enters a loop from the incremented
indexup to the length of thedataarray. - Inside the loop, it assigns the current character of the
dataarray toch. - It checks for a switch case where
chis equal to theSTRING_END_TOKEN.- If so, it updates the
indexvariable to the current index and returns the index. - If not, it continues to the next step.
- If so, it updates the
- It then checks if
chis greater than or equal toSPACE_WS. If true, it continues to the next iteration of the loop. - If the character doesn't match the switch case and is not greater than
SPACE_WS, it throws anUnexpectedCharacterExceptionwith the appropriate message, passing in this object,ch, and the current index. - If the loop completes without finding a match, it throws an
UnexpectedCharacterExceptionwith the appropriate message, passing in this object,ch, and the current index.
Note: The specific values for STRING_END_TOKEN and SPACE_WS are not included in the code snippet provided and may be defined elsewhere in the codebase or imported from another class or module.

public NumberParseResult findEndOfNumber()
@Override
public NumberParseResult findEndOfNumber() {
final char startCh = getCurrentChar();
final int startIndex = index;
char ch = startCh;
int i = index + 1;
final char[] data = this.data;
final int endIndex = this.sourceEndIndex;
loop: for (; i < endIndex; i++) {
ch = data[i];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
case ATTRIBUTE_SEP:
case ARRAY_SEP:
case OBJECT_END_TOKEN:
case ARRAY_END_TOKEN:
break loop;
case NUM_0:
case NUM_1:
case NUM_2:
case NUM_3:
case NUM_4:
case NUM_5:
case NUM_6:
case NUM_7:
case NUM_8:
case NUM_9:
break;
case DECIMAL_POINT:
if (startCh == MINUS) {
final int numLenSoFar = i - startIndex;
if (numLenSoFar == 1) {
throw new UnexpectedCharacterException("Parsing JSON Number", "Unexpected character", this, ch, i);
}
}
index = i;
return findEndOfFloat();
case EXPONENT_MARKER:
case EXPONENT_MARKER2:
index = i;
return parseFloatWithExponent();
default:
throw new UnexpectedCharacterException("Parsing JSON Number", "Unexpected character", this, ch, i);
}
}
index = i;
final int numLength = i - startIndex;
switch(startCh) {
case NUM_0:
if (numLength != 1) {
throw new UnexpectedCharacterException("Parsing JSON Int Number", "Int can't start with a 0 ", this, startCh, startIndex);
}
break;
case PLUS:
throw new UnexpectedCharacterException("Parsing JSON Int Number", "Int can't start with a plus ", this, startCh, startIndex);
case MINUS:
switch(numLength) {
case 1:
throw new UnexpectedCharacterException("Parsing JSON Int Number", "Int can't be only a minus, number is missing", this, startCh, startIndex);
case 2:
break;
default:
if (data[startIndex + 1] == NUM_0) {
throw new UnexpectedCharacterException("Parsing JSON Int Number", "0 can't be after minus sign", this, startCh, startIndex);
}
}
}
return new NumberParseResult(i - this.sourceStartIndex, false);
}The method findEndOfNumber in the class io.nats.jparse.source.CharArrayOffsetCharSource is responsible for finding the end of a number while parsing JSON data. Here is the step-by-step description of what this method does based on its code:
- It retrieves the current character from the source and assigns it to the variable
startCh. - It sets the starting index to the current index.
- It initializes the variable
chwith the value ofstartChand increments the variableiby 1. - It retrieves the character array
dataand the end indexendIndexfrom the source. - It enters a loop that iterates over the characters from
itoendIndex. - For each character
chin the loop:- If the character is one of the following:
NEW_LINE_WS,CARRIAGE_RETURN_WS,TAB_WS,SPACE_WS,ATTRIBUTE_SEP,ARRAY_SEP,OBJECT_END_TOKEN, orARRAY_END_TOKEN, the loop breaks. - If the character is one of the digits
NUM_0toNUM_9, the loop continues. - If the character is a
DECIMAL_POINTand thestartChisMINUS, it checks if the length of the number is 1. If it is, it throws an exception. Then, it sets the current index toiand returns the result of calling thefindEndOfFloatmethod. - If the character is an
EXPONENT_MARKERor anEXPONENT_MARKER2, it sets the current index toiand returns the result of calling theparseFloatWithExponentmethod. - If none of the above conditions match, it throws an exception.
- If the character is one of the following:
- It sets the current index to
i. - It calculates the length of the number by subtracting the starting index from
iand assigns it tonumLength. - It checks the value of the
startChcharacter:- If it is
NUM_0, it checks ifnumLengthis not equal to 1. If it is not, it throws an exception. - If it is
PLUS, it throws an exception. - If it is
MINUS, it checks the value ofnumLength:- If it is 1, it throws an exception.
- If it is 2, it continues.
- If it is greater than 2 and the character following the
MINUSisNUM_0, it throws an exception.
- If it is
- It creates a new
NumberParseResultobject with the length of the number (i -this.sourceStartIndex) and the valuefalse. - It returns the
NumberParseResultobject.
private NumberParseResult findEndOfFloat() {
int i = index + 1;
char ch = (char) next();
if (!isNumber(ch)) {
throw new UnexpectedCharacterException("Parsing float part of number", "After decimal point expecting number but got", this, ch, this.index);
}
final char[] data = this.data;
final int endIndex = this.sourceEndIndex;
for (; i < endIndex; i++) {
ch = data[i];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
case ATTRIBUTE_SEP:
case ARRAY_SEP:
case OBJECT_END_TOKEN:
case ARRAY_END_TOKEN:
index = i;
return new NumberParseResult(i - sourceStartIndex, true);
case NUM_0:
case NUM_1:
case NUM_2:
case NUM_3:
case NUM_4:
case NUM_5:
case NUM_6:
case NUM_7:
case NUM_8:
case NUM_9:
break;
case EXPONENT_MARKER:
case EXPONENT_MARKER2:
index = i;
return parseFloatWithExponent();
default:
throw new UnexpectedCharacterException("Parsing JSON Float Number", "Unexpected character", this, ch, i);
}
}
index = i;
return new NumberParseResult(i - sourceStartIndex, true);
}The method findEndOfFloat in the CharArrayOffsetCharSource class is used to find the end of a floating-point number in a JSON input string. Here is a step-by-step description of what the method does:
-
The method initializes a local variable
ito the value ofindex + 1and retrieves the next characterchfrom the input stream using thenext()method. -
It checks if the character
chis not a valid number character. If it's not, it throws anUnexpectedCharacterException, indicating that a number was expected after the decimal point but a different character was encountered. -
The method then retrieves the underlying character array
dataand the end index of the source string. -
It enters a loop that iterates from
itoendIndex. -
Inside the loop, the method checks the current character
chagainst a series of predefined characters that can signal the end of a floating-point number. These characters include whitespace characters (NEW_LINE_WS,CARRIAGE_RETURN_WS,TAB_WS,SPACE_WS), attribute and array separators (ATTRIBUTE_SEP,ARRAY_SEP), and object and array end tokens (OBJECT_END_TOKEN,ARRAY_END_TOKEN). If a match is found, the method updates theindexvariable to the current value ofiand returns a newNumberParseResultobject containing the length of the parsed number asi - sourceStartIndexand a flag indicating that the number is complete (true). -
If the current character
chis not one of the predefined end tokens, the method checks if it's a digit (NUM_0toNUM_9). If it is, the loop continues to the next iteration. This allows the method to handle numbers with digits after the decimal point. -
If the current character
chis an exponent marker (EXPONENT_MARKERorEXPONENT_MARKER2), the method updates theindexvariable to the current value ofiand returns the result of calling theparseFloatWithExponent()method. This method handles parsing floating-point numbers with exponent notation. -
If none of the above conditions are met, the method throws an
UnexpectedCharacterException, indicating that an unexpected character was encountered while parsing the JSON float number. -
After the loop completes without finding an end token, the method updates the
indexvariable to the current value ofiand returns a newNumberParseResultobject containing the length of the parsed number asi - sourceStartIndexand a flag indicating that the number is complete (true).
private boolean isNumber(final char ch) {
switch(ch) {
case NUM_0:
case NUM_1:
case NUM_2:
case NUM_3:
case NUM_4:
case NUM_5:
case NUM_6:
case NUM_7:
case NUM_8:
case NUM_9:
return true;
default:
return false;
}
}The isNumber method in the CharArrayOffsetCharSource class is used to determine whether a given character is a number. Here is a step-by-step description of how the method works:
-
The method takes a
charparameter calledch. -
It uses a switch statement to check the value of the
chcharacter. -
The
casestatements in the switch statement represent the numbers0to9. -
If the value of
chmatches any of the cases (i.e., it is a number), the method returnstrue. -
If the value of
chdoes not match any of the cases (i.e., it is not a number), the method returnsfalse.
That's the step-by-step description of how the isNumber method in the CharArrayOffsetCharSource class works.

private NumberParseResult parseFloatWithExponent() {
char ch = (char) next();
if (!isNumberOrSign(ch)) {
throw new UnexpectedCharacterException("Parsing exponent part of float", "After exponent expecting number or sign but got", this, ch, this.index);
}
if (isSign(ch)) {
ch = (char) next();
if (!isNumber(ch)) {
throw new UnexpectedCharacterException("Parsing exponent part of float after sign", "After sign expecting number but got", this, ch, this.index);
}
}
int i = index + 1;
final char[] data = this.data;
final int endIndex = this.sourceEndIndex;
for (; i < endIndex; i++) {
ch = data[i];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
case ATTRIBUTE_SEP:
case ARRAY_SEP:
case OBJECT_END_TOKEN:
case ARRAY_END_TOKEN:
index = i;
return new NumberParseResult(i - sourceStartIndex, true);
case NUM_0:
case NUM_1:
case NUM_2:
case NUM_3:
case NUM_4:
case NUM_5:
case NUM_6:
case NUM_7:
case NUM_8:
case NUM_9:
break;
default:
throw new UnexpectedCharacterException("Parsing Float with exponent", "Unable to find closing for Number", this, ch, i);
}
}
index = i;
return new NumberParseResult(i - sourceStartIndex, true);
}The method parseFloatWithExponent in the CharArrayOffsetCharSource class is used to parse a floating-point number with an exponent. Below is a step-by-step description of what the method does:
- The method starts by fetching the next character from the input stream and assigns it to the variable
ch. - It checks if the character
chis a valid number or sign character using theisNumberOrSignmethod. If it is not, it throws anUnexpectedCharacterExceptionwith an appropriate error message. - If the character
chis a sign character, it fetches the next character and assigns it toch. If the next character is not a number, it throws anUnexpectedCharacterExceptionwith an appropriate error message. - It initializes a variable
iwith the value ofindex + 1, which represents the next index to start parsing at. - It assigns the internal character array
datafrom theCharArrayOffsetCharSourceinstance to a local variabledata. - It assigns the value of
sourceEndIndexto a local variableendIndex, which represents the end index of the source. - It enters a
forloop that iterates fromitoendIndex. - Inside the loop, it assigns the character at index
iin thedataarray toch. - It checks if
chis one of the following characters:NEW_LINE_WS,CARRIAGE_RETURN_WS,TAB_WS,SPACE_WS,ATTRIBUTE_SEP,ARRAY_SEP,OBJECT_END_TOKEN, orARRAY_END_TOKEN. If it is, it updates theindexvariable toiand returns a newNumberParseResultobject with the length of the parsed number (i - sourceStartIndex) andtrueindicating success. - If
chis one of the digit charactersNUM_0toNUM_9, it continues the loop iteration without any special action. - If
chdoes not match any of the above cases, it throws anUnexpectedCharacterExceptionwith an appropriate error message. - After the loop exits, it updates the
indexvariable toiand returns a newNumberParseResultobject with the length of the parsed number (i - sourceStartIndex) andtrueindicating success.
Overall, the method iterates through the characters starting from the initial index and checks if each character is a valid part of the exponent part of a floating-point number. It stops parsing when it encounters a character that is not part of the exponent or reaches the end of the input.

private boolean isNumberOrSign(char ch) {
switch(ch) {
case NUM_0:
case NUM_1:
case NUM_2:
case NUM_3:
case NUM_4:
case NUM_5:
case NUM_6:
case NUM_7:
case NUM_8:
case NUM_9:
case MINUS:
case PLUS:
return true;
default:
return false;
}
}The isNumberOrSign method is defined in the io.nats.jparse.source.CharArrayOffsetCharSource class. It is a private method that takes a single character as input and returns a boolean value.
The purpose of this method is to determine whether a given character is a number or a mathematical sign (either a minus or plus symbol).
The method contains a switch-case statement that checks the input character against several predefined constants representing the digits 0-9, as well as the minus and plus signs.
- If the input character matches any of these constants, the method will return
true, indicating that the character is a number or a sign. - If the input character does not match any of the constants, the method will return
false, indicating that the character is not a number or a sign.
Here is the step-by-step description of the isNumberOrSign method based on its body:
-
Declare a private boolean method named
isNumberOrSignthat takes a single characterchas input. -
Start a switch-case statement to check the value of
ch. -
In each case, compare the value of
chto the following constants:-
NUM_0, representing the character '0' -
NUM_1, representing the character '1' -
NUM_2, representing the character '2' -
NUM_3, representing the character '3' -
NUM_4, representing the character '4' -
NUM_5, representing the character '5' -
NUM_6, representing the character '6' -
NUM_7, representing the character '7' -
NUM_8, representing the character '8' -
NUM_9, representing the character '9' -
MINUS, representing the minus sign '-' -
PLUS, representing the plus sign '+'
-
-
If
chmatches any of the above constants, returntrueto indicate thatchis a number or a sign. -
If
chdoes not match any of the above constants, returnfalseto indicate thatchis not a number or a sign. -
End the method.

private boolean isSign(char ch) {
switch(ch) {
case MINUS:
case PLUS:
return true;
default:
return false;
}
}The isSign method in the io.nats.jparse.source.CharArrayOffsetCharSource class is used to determine whether a given character is a sign symbol. It follows these steps:
- The method takes a character
chas a parameter. - It enters a switch statement, which checks the value of
ch. - If
chis equal to theMINUSconstant or thePLUSconstant (presumably defined in the class or imported from another class), the method returnstrue. - If
chdoes not match any of the case values, the method returnsfalse.
To summarize, the isSign method checks if a character is a sign symbol (- or +) and returns true if it is, or false if it is not.

public int findFalseEnd()
@Override
public int findFalseEnd() {
if (this.data[++index] == 'a' && this.data[++index] == 'l' && this.data[++index] == 's' && this.data[++index] == 'e') {
return ++index - sourceStartIndex;
} else {
throw new UnexpectedCharacterException("Parsing JSON False Boolean", "Unexpected character", this);
}
}The findFalseEnd method in the io.nats.jparse.source.CharArrayOffsetCharSource class is defined as follows:
- The method starts by incrementing the
indexvariable and checks if the character at the updated index is equal to 'a'. - If the character is 'a', the method then increments the
indexvariable again and checks if the character at the updated index is equal to 'l'. - If the character is 'l', the method again increments the
indexvariable and checks if the character at the updated index is equal to 's'. - If the character is 's', the method once more increments the
indexvariable and checks if the character at the updated index is equal to 'e'. - If all of the characters 'a', 'l', 's', and 'e' are found consecutively, the method returns the value of the incremented
indexvariable minus thesourceStartIndexvariable. - If any of the characters are not found consecutively or the end of the source is reached before finding the complete sequence, an
UnexpectedCharacterExceptionis thrown, with the message "Parsing JSON False Boolean" and "Unexpected character", and the instance of theCharArrayOffsetCharSourceclass is passed as an argument to the exception.
public int findTrueEnd()
@Override
public int findTrueEnd() {
if (this.data[++index] == 'r' && this.data[++index] == 'u' && this.data[++index] == 'e') {
return ++index - sourceStartIndex;
} else {
throw new UnexpectedCharacterException("Parsing JSON True Boolean", "Unexpected character", this);
}
}The method findTrueEnd is implemented in the class io.nats.jparse.source.CharArrayOffsetCharSource. Its purpose is to find the end position of a boolean value "true" within a JSON source string.
Here is a step-by-step description of what the method does:
- Increment the
indexvalue by 1 and check if the character at the new index position in thedataarray is equal to 'r'. - If the character at the new index position is 'r', increment the
indexvalue by 1 again and check if the character at the new index position is equal to 'u'. - If the character at the new index position is 'u', increment the
indexvalue by 1 once more and check if the character at the new index position is equal to 'e'. - If all the characters 'r', 'u', and 'e' are found one after another, it means the end of the boolean value "true" has been found.
- Return the value of
++index - sourceStartIndex, which represents the length of the substring containing the boolean value "true".
- Return the value of
- If any of the characters is not found in the expected sequence, it means there is an unexpected character, and an exception of type
UnexpectedCharacterExceptionis thrown.- The exception message will indicate that an unexpected character was encountered while parsing the JSON True Boolean value.
- The exception will also contain a reference to the
CharArrayOffsetCharSourceobject that encountered the unexpected character.
This method is useful for parsing a JSON source string and identifying the end position of the boolean value "true".

public boolean findObjectEndOrAttributeSep()
@Override
public boolean findObjectEndOrAttributeSep() {
int i = index;
char ch = 0;
final char[] data = this.data;
final int end = sourceEndIndex;
for (; i < end; i++) {
ch = data[i];
switch(ch) {
case OBJECT_END_TOKEN:
this.index = i + 1;
return true;
case ATTRIBUTE_SEP:
this.index = i;
return false;
}
}
throw new UnexpectedCharacterException("Parsing Object Key", "Finding object end or separator", this);
}The findObjectEndOrAttributeSep method is defined in the CharArrayOffsetCharSource class in the io.nats.jparse.source package. It is used to find the end of an object or the separator within the source data.
Here is a step-by-step description of what the method does:
- The method overrides the
findObjectEndOrAttributeSepmethod defined in the superclass. - It initializes the local variables
ito the current index andchto 0. - It retrieves the source data array and assigns it to the local variable
data. - It retrieves the end index of the source and assigns it to the local variable
end. - It starts a loop from the current index
iuntil the end indexend. - Within the loop, it retrieves the character at index
ifrom the source data array and assigns it toch. - It then performs a switch-case on the character
ch. - If the character is equal to the object end token, it updates the index to
i + 1, indicating that the end of the object has been found, and returnstrue. - If the character is equal to the attribute separator, it updates the index to
i, indicating that the separator has been found, and returnsfalse. - If none of the above cases match, it continues to the next iteration of the loop.
- If the loop completes without finding the object end or separator, it throws an
UnexpectedCharacterExceptionwith an appropriate error message. - The error message specifies that the error occurred while parsing an object key and while finding the object end or separator.
- The
thisreference passed to the exception constructor refers to the currentCharArrayOffsetCharSourceinstance.
This method provides functionality to find the end of an object or the separator within the source data, allowing for efficient parsing of JSON-like data structures.

public boolean findCommaOrEndForArray()
@Override
public boolean findCommaOrEndForArray() {
int i = index;
char ch = 0;
final char[] data = this.data;
final int end = sourceEndIndex;
for (; i < end; i++) {
ch = data[i];
switch(ch) {
case ARRAY_END_TOKEN:
this.index = i + 1;
return true;
case ARRAY_SEP:
this.index = i;
return false;
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
continue;
default:
throw new UnexpectedCharacterException("Parsing Object Key", "Finding object end or separator", this, ch, i);
}
}
throw new UnexpectedCharacterException("Parsing Array", "Finding list end or separator", this);
}The findCommaOrEndForArray() method is defined in the io.nats.jparse.source.CharArrayOffsetCharSource class. It is an override method that returns a boolean value.
Here is a step-by-step description of what the findCommaOrEndForArray() method does based on its body:
- Declare a variable
iand initialize it with the currentindexvalue. - Declare a variable
chand initialize it with0. - Assign the
dataarray from the class to a local variabledata. - Extract the
endvalue from thesourceEndIndexvariable. - Start a loop from the current
indexvalue (i) to theendvalue. - Get the current character
chfromdata[i]. - Perform a switch case on
ch.- If
chis equal toARRAY_END_TOKEN:- Update the class
indexvalue toi + 1. - Return
trueto indicate that an array end has been found.
- Update the class
- If
chis equal toARRAY_SEP:- Update the class
indexvalue toi. - Return
falseto indicate that a comma separator has been found.
- Update the class
- If
chis equal to any of the whitespace characters (NEW_LINE_WS,CARRIAGE_RETURN_WS,TAB_WS,SPACE_WS):- Continue to the next iteration of the loop.
- If
chis not equal to any of the above characters:- Throw an
UnexpectedCharacterExceptionwith the appropriate message, indicating that an unexpected character was found while parsing the object key or finding the object end or separator.
- Throw an
- If
- If the loop completes without finding an array end or separator, throw an
UnexpectedCharacterExceptionwith the appropriate message, indicating that an unexpected character was found while parsing the array or finding the list end or separator.
public int findNullEnd()
@Override
public int findNullEnd() {
if (this.data[++index] == 'u' && this.data[++index] == 'l' && this.data[++index] == 'l') {
return ++index - sourceStartIndex;
} else {
throw new UnexpectedCharacterException("Parsing JSON Null", "Unexpected character", this);
}
}The findNullEnd method in the io.nats.jparse.source.CharArrayOffsetCharSource class is designed to find the end of the string "null" within the provided character array.
Here is the step-by-step description of what this method does:
-
The method starts with the
indexvariable pointing to the current position in the character array. -
It checks if the character at the next position in the array after
indexis 'u'. -
If the character at the next position is 'u', it then checks if the next character after 'u' is 'l'.
-
If the character at the next position after 'l' is also 'l', it means that the string "null" has been found.
-
In that case, the method returns the current
indexvalue incremented by 1 and subtracted bysourceStartIndex. This calculation gives the length of the matched "null" string within the character array. -
If the characters 'u', 'l', and 'l' are not found in sequence, it means that an unexpected character has been encountered while parsing the JSON string.
-
In such cases, the method throws an
UnexpectedCharacterException, providing a descriptive message indicating that an unexpected character was found.
In summary, the findNullEnd method searches for the string "null" within a character array and returns the length of the matched string, or throws an exception if an unexpected character is encountered.

public boolean matchChars(final int startIndex, final int endIndex, CharSequence key)
@Override
public boolean matchChars(final int startIndex, final int endIndex, CharSequence key) {
final int length = endIndex - startIndex;
final int offset = this.sourceStartIndex;
int idx = startIndex + offset;
switch(length) {
case 1:
return key.charAt(0) == data[idx];
case 2:
return key.charAt(0) == data[idx] && key.charAt(1) == data[idx + 1];
case 3:
return key.charAt(0) == data[idx] && key.charAt(1) == data[idx + 1] && key.charAt(2) == data[idx + 2];
case 4:
return key.charAt(0) == data[idx] && key.charAt(1) == data[idx + 1] && key.charAt(2) == data[idx + 2] && key.charAt(3) == data[idx + 3];
case 5:
return key.charAt(1) == data[idx + 1] && key.charAt(3) == data[idx + 3] && key.charAt(0) == data[idx] && key.charAt(2) == data[idx + 2] && key.charAt(4) == data[idx + 4];
case 6:
return key.charAt(0) == data[idx] && key.charAt(5) == data[idx + 5] && key.charAt(3) == data[idx + 3] && key.charAt(1) == data[idx + 1] && key.charAt(2) == data[idx + 2] && key.charAt(4) == data[idx + 4];
case 7:
return key.charAt(0) == data[idx] && key.charAt(6) == data[idx + 6] && key.charAt(3) == data[idx + 3] && key.charAt(1) == data[idx + 1] && key.charAt(5) == data[idx + 5] && key.charAt(2) == data[idx + 2] && key.charAt(4) == data[idx + 4];
case 8:
return key.charAt(0) == data[idx] && key.charAt(7) == data[idx + 7] && key.charAt(3) == data[idx + 3] && key.charAt(1) == data[idx + 1] && key.charAt(5) == data[idx + 5] && key.charAt(2) == data[idx + 2] && key.charAt(6) == data[idx + 6] && key.charAt(4) == data[idx + 4];
case 9:
return key.charAt(0) == data[idx] && key.charAt(8) == data[idx + 8] && key.charAt(2) == data[idx + 2] && key.charAt(6) == data[idx + 6] && key.charAt(3) == data[idx + 3] && key.charAt(7) == data[idx + 7] && key.charAt(4) == data[idx + 4] && key.charAt(5) == data[idx + 5] && key.charAt(1) == data[idx + 1];
case 10:
return key.charAt(0) == data[idx] && key.charAt(9) == data[idx + 9] && key.charAt(6) == data[idx + 6] && key.charAt(3) == data[idx + 3] && key.charAt(7) == data[idx + 7] && key.charAt(2) == data[idx + 2] && key.charAt(4) == data[idx + 4] && key.charAt(5) == data[idx + 5] && key.charAt(1) == data[idx + 1] && key.charAt(8) == data[idx + 8];
case 11:
return key.charAt(0) == data[idx] && key.charAt(10) == data[idx + 10] && key.charAt(6) == data[idx + 6] && key.charAt(3) == data[idx + 3] && key.charAt(7) == data[idx + 7] && key.charAt(2) == data[idx + 2] && key.charAt(9) == data[idx + 9] && key.charAt(4) == data[idx + 4] && key.charAt(5) == data[idx + 5] && key.charAt(1) == data[idx + 1] && key.charAt(8) == data[idx + 8];
case 12:
return key.charAt(0) == data[idx] && key.charAt(11) == data[idx + 11] && key.charAt(3) == data[idx + 3] && key.charAt(7) == data[idx + 7] && key.charAt(2) == data[idx + 2] && key.charAt(6) == data[idx + 6] && key.charAt(9) == data[idx + 9] && key.charAt(4) == data[idx + 4] && key.charAt(5) == data[idx + 5] && key.charAt(10) == data[idx + 10] && key.charAt(1) == data[idx + 1] && key.charAt(8) == data[idx + 8];
default:
final int start = 0;
final int end = length - 1;
final int middle = length / 2;
if (key.charAt(start) == data[idx] && key.charAt(end) == data[idx + end] && key.charAt(middle) == data[idx + middle]) {
for (int i = 1; i < length; i++) {
if (key.charAt(i) != data[idx + i]) {
return false;
}
}
return true;
} else {
return false;
}
}
}This method is defined in the class io.nats.jparse.source.CharArrayOffsetCharSource and is used to match a sequence of characters from the provided startIndex to endIndex with the given key. The method returns a boolean value indicating whether the characters match or not.
public boolean matchChars(final int startIndex, final int endIndex, CharSequence key)-
startIndex(int): The starting index of the character sequence to match. -
endIndex(int): The ending index of the character sequence to match. -
key(CharSequence): The key to match against the character sequence.
- Calculate the length of the character sequence by taking the difference between the
startIndexandendIndexparameters. - Get the offset from the
sourceStartIndexin the class. - Initialize the
idxvariable by adding thestartIndexto the offset. - Use a switch statement based on the length of the character sequence to handle different cases:
- If the length is 1, compare the first character of the
keywith the character atdata[idx]and return the result. - If the length is 2, compare the first two characters of the
keywith the characters atdata[idx]anddata[idx + 1]respectively and return the result. - Repeat the above steps for different cases of length 3 to 12, comparing the characters one by one.
- For any other length, do the following:
- Set the start, end, and middle indices based on the length.
- Check if the first, last, and middle characters of
keymatch the corresponding characters indata[idx]anddata[idx + end]anddata[idx + middle]respectively. - If the characters match, iterate through the remaining characters of
keyand compare them with the corresponding characters indata[idx + i]. - If any character mismatch is found, return false.
- If all characters match, return true.
- If the length is 1, compare the first character of the
- If none of the above cases match, return false.
public boolean isInteger(int startIndex, int endIndex) {
int len = endIndex - startIndex;
int offset = this.sourceStartIndex;
final char[] digitChars = data;
final boolean negative = (digitChars[startIndex] == '-');
final int cmpLen = negative ? MIN_INT_STR_LENGTH : MAX_INT_STR_LENGTH;
if (len < cmpLen)
return true;
if (len > cmpLen)
return false;
final char[] cmpStr = negative ? MIN_INT_CHARS : MAX_INT_CHARS;
for (int i = 0; i < cmpLen; ++i) {
int diff = digitChars[startIndex + i + offset] - cmpStr[i];
if (diff != 0) {
return (diff < 0);
}
}
return true;
}The method isInteger in class io.nats.jparse.source.CharArrayOffsetCharSource can be described in the following steps:
- Calculate the length of the input range given by
endIndex - startIndexand assign it to the variablelen. - Set the offset of the source index to the
sourceStartIndexof the object. - Assign the character array
datato the local variabledigitChars. - Check if the first character at the
startIndexofdigitCharsis a negative sign'-'and assign the result to thenegativevariable. - Determine the comparison length based on whether the number is negative or not. If it's negative, the comparison length should be
MIN_INT_STR_LENGTH, otherwise it should beMAX_INT_STR_LENGTH, and assign the result tocmpLen. - If the
lenis less thancmpLen, returntrueas it means the number cannot be an integer. - If the
lenis greater thancmpLen, returnfalseas it means the number cannot be an integer. - Determine the comparison string based on whether the number is negative or not. If it's negative, use
MIN_INT_CHARS, otherwise useMAX_INT_CHARS, and assign the result tocmpStr. - Loop through each character in the comparison range
(startIndex + i + offset)and compare it with the corresponding character incmpStr. - Subtract the characters from
digitCharsandcmpStrand store the difference in the variablediff. - If
diffis not equal to zero, returntrueifdiffis less than zero, indicating that the number is less than the comparison string. Otherwise, returnfalseas the number is greater than the comparison string. - If the loop completes without returning, return
trueas the number is equal to the comparison string.
public String errorDetails(String message, int index, int ch)
@Override
public String errorDetails(String message, int index, int ch) {
StringBuilder buf = new StringBuilder(255);
final char[] array = data;
buf.append(message).append("\n");
buf.append("\n");
buf.append("The current character read is " + debugCharDescription(ch)).append('\n');
int line = 0;
int lastLineIndex = 0;
for (int i = 0; i < index && i < array.length; i++) {
if (array[i] == '\n') {
line++;
lastLineIndex = i + 1;
}
}
int count = 0;
for (int i = lastLineIndex; i < array.length; i++, count++) {
if (array[i] == '\n') {
break;
}
}
buf.append("line number " + (line + 1)).append('\n');
buf.append("index number " + index).append('\n');
buf.append("offset index number " + index + sourceStartIndex).append('\n');
try {
buf.append(new String(array, lastLineIndex, count)).append('\n');
} catch (Exception ex) {
try {
int start = index = (index - 10 < 0) ? 0 : index - 10;
buf.append(new String(array, start, index)).append('\n');
} catch (Exception ex2) {
buf.append(new String(array)).append('\n');
}
}
for (int i = 0; i < (index - lastLineIndex); i++) {
buf.append('.');
}
buf.append('^');
return buf.toString();
}The errorDetails method in the CharArrayOffsetCharSource class is a method that generates an error debug message with details about the error in the source code at a given index.
Here is a step-by-step description of the method:
- Create a new
StringBuildercalledbufto store the error debug message. - Append the input
messagetobuffollowed by a new line character ("\n"). - Append an empty line to
buf. - Append a description of the current character being read, obtained from the
debugCharDescriptionmethod, tobuf. - Initialize two variables:
lineandlastLineIndex.lineis set to 0 andlastLineIndexis set to 0. - Iterate through the character array
datastarting from index 0 up to the givenindex(the index of the error in the source code). a. If the current character in the array is a new line character ('\n'), incrementlineby 1 and updatelastLineIndexto the current index plus 1. - Initialize a
countvariable to 0. - Iterate through the character array
datastarting fromlastLineIndexup to the end of the array. a. If the current character in the array is a new line character ('\n'), break the loop. b. Otherwise, incrementcountby 1. - Append the line number (calculated as
line + 1) tobuffollowed by a new line character. - Append the index number to
buffollowed by a new line character. - Append the offset index number (calculated as
index + sourceStartIndex) tobuffollowed by a new line character. - Try to append a substring of the character array
datastarting fromlastLineIndexwith a length ofcounttobuf. If an exception occurs, move to the next step. - If an exception occurs during step 12, try to append a substring of the character array
datastarting from(index - 10 < 0) ? 0 : index - 10with a length ofindextobuf. If this also fails, move to the next step. - If an exception occurs during step 13, append the entire character array
datatobuf. - Append a number of dots equal to
(index - lastLineIndex)tobuf. - Append a caret (
^) character tobuf. - Return the resulting string from
bufas the error debug message.
The Sources class provides utility methods for creating CharSource objects from various input sources, such as strings, byte arrays, files, input streams, and readers. It allows you to easily create CharSource objects from different types of input sources, including strings, byte arrays, files, input streams, and readers. It also provides different methods for creating CharSource objects from specific input types, such as CharSequence, String, byte array, char array, CharBuffer, file, input stream, and Reader. The class handles conversions and error handling for each input type, making it convenient to create CharSource objects for different use cases.
public static CharSource charSeqSource(final CharSequence source) {
if (source instanceof String) {
return new CharArrayCharSource((String) source);
} else {
return new CharArrayCharSource(source.toString());
}
}The charSeqSource method, defined in the Sources class in the io.nats.jparse.source package, is a public static method that takes a CharSequence parameter named source. The method returns a CharSource object based on the input source.
Here is a step-by-step description of what the charSeqSource method does:
-
If the
sourceparameter is an instance of theStringclass:- Create a new
CharArrayCharSourceobject, passing in thesourceparameter (which is casted to aString) as the constructor argument. - Return the newly created
CharArrayCharSourceobject.
- Create a new
-
If the
sourceparameter is not an instance of theStringclass:- Convert the
sourceparameter to a string by invoking thetoString()method on it. - Create a new
CharArrayCharSourceobject, passing in the converted string as the constructor argument. - Return the newly created
CharArrayCharSourceobject.
- Convert the
Note: The CharSource class is not defined in the given code snippet. However, it is assumed to be a class or interface that is imported and accessible within the Sources class.

public static CharSource fileSource(final String fileNameSource, final Charset charset) {
try {
return byteSource(Files.readAllBytes(Paths.get(fileNameSource)), charset);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}The fileSource method in the io.nats.jparse.source.Sources class is responsible for creating a CharSource object based on the contents of a file specified by the fileNameSource parameter.
Here are the steps performed by the fileSource method:
- The method takes two parameters:
fileNameSource, which specifies the file name or path, andcharset, which specifies the character set to use for reading the file. - Inside a try-catch block, the method calls the static method
Files.readAllBytesto read all the bytes from the file specified byfileNameSource. This method returns abyte[]array containing the contents of the file. - The
byteSourcemethod is then called, passing thebyte[]array and thecharsetparameter. This method creates and returns aCharSourceobject based on the provided byte array and character set. - If an
IOExceptionoccurs during the file reading process, the catch block catches the exception and throws a newIllegalStateExceptionwith the caught exception as the cause.
In summary, the fileSource method reads the contents of a file specified by fileNameSource and returns a CharSource object representing the file's content using the specified character set.

public static CharSource fileSource(final File fileSource, final Charset charset) {
try {
return byteSource(Files.readAllBytes(Paths.get(fileSource.getAbsolutePath())), charset);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}The method fileSource defined in the class io.nats.jparse.source.Sources is used to create a CharSource from a file. Here is a step-by-step description of what the method does based on its body:
-
The method takes two parameters:
fileSourceof typeFile, which represents the file to read, andcharsetof typeCharset, which specifies the character encoding to use for reading the file. -
Inside the method, a try-catch block is used to handle any potential
IOExceptionthat might occur when reading the file. -
The method calls the
Files.readAllBytesmethod, passing in the absolute path of thefileSourcefile. This method reads all the bytes from the file and returns them as a byte array. -
The method then calls another method called
byteSource, passing in the byte array obtained from the previous step and thecharsetprovided as arguments. It is not clear from the given code snippet what thisbyteSourcemethod does, but it is likely used to convert the byte array into aCharSourceusing the specified character encoding. -
If an
IOExceptionoccurs during the file reading process, the catch block is executed. In this case, anIllegalStateExceptionis thrown, wrapping the originalIOExceptionthat was caught. -
The method ends, either returning the resulting
CharSourceif the file reading process was successful, or throwing an exception if an error occurred.
public static CharSource readerSource(final Reader readerSource) {
final BufferedReader reader = new BufferedReader(readerSource);
StringBuilder stringBuilder = new StringBuilder();
try {
String s = reader.readLine();
while (s != null) {
stringBuilder.append(s).append('\n');
s = reader.readLine();
}
} catch (Exception ex) {
throw new IllegalStateException(ex);
} finally {
try {
reader.close();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
return new CharArrayCharSource(stringBuilder.toString());
}The readerSource method in class io.nats.jparse.source.Sources is used to convert a Reader object into a CharSource object. Here is a step-by-step description of what the method does:
-
The method takes a
Readerobject as an input parameter namedreaderSource. -
It creates a new
BufferedReaderobject namedreaderby passing thereaderSourceto its constructor. -
It creates a
StringBuilderobject namedstringBuilderto store the contents of thereader. -
The method surrounds the following code block with a try-catch block to handle any exceptions that may occur:
String s = reader.readLine(); while (s != null) { stringBuilder.append(s).append('\n'); s = reader.readLine(); }
- It initializes a
Stringvariableswith the first line read from thereaderusing thereadLine()method. - It enters a
whileloop that continues untilsisnull. - Inside the loop, it appends the value of
stostringBuilder, followed by a newline character'\n'. - It reads the next line from
readerand assigns it tos.
- It initializes a
-
If any exception occurs during the execution of the code block, an
IllegalStateExceptionis thrown, with the caught exception as its cause. -
After the try-catch block, a
finallyblock is used to ensure that thereaderis properly closed. It is closed by calling theclose()method on thereader. If anIOExceptionoccurs while closing thereader, anIllegalStateExceptionis thrown, with the caught exception as its cause. -
Finally, the method creates a new
CharArrayCharSourceobject by passing the contents ofstringBuilderas aStringto its constructor. -
The method returns the created
CharSourceobject.
This method basically reads the contents of a Reader object line by line, appends each line to a StringBuilder, and converts the resulting string into a CharSource object.

This class is a char source for char arrays. It is used by the parser to parse strings and is not thread safe. It is not a general-purpose char source.
public static String debugCharDescription(int c) {
String charString;
if (c == ' ') {
charString = "[SPACE]";
} else if (c == '\t') {
charString = "[TAB]";
} else if (c == '\n') {
charString = "[NEWLINE]";
} else if (c == ETX) {
charString = "ETX";
} else {
charString = "'" + (char) c + "'";
}
charString = charString + " with an int value of " + c;
return charString;
}This method is defined in the io.nats.jparse.source.CharArrayCharSource class. Its purpose is to return a debug description of a given character by converting it to a string representation.
-
c(int): The input character to be debugged.
- The method returns a string representation of the input character, along with additional debug information.
- Initialize the variable
charStringto store the debug description of the character. - Check if the input character
cis equal to a space character (' '). - If true, assign
"[SPACE]"tocharString. - If the character is not a space, check if it is a tab character (
' '). - If true, assign
"[TAB]"tocharString. - If the character is not a tab, check if it is a newline character (
'\n'). - If true, assign
"[NEWLINE]"tocharString. - If the character is not a newline, check if it is equal to a specific constant
ETX. - If true, assign
"ETX"tocharString. - If the character does not match any of the previous conditions, it is considered a regular character.
- Assign the character surrounded by single quotes (
') tocharString. - Concatenate the string
" with an int value of "and the value ofctocharString. - Return the value of
charStringas the debug description of the character.
public int next()
@Override
public int next() {
if (index + 1 >= data.length) {
index = data.length;
return ETX;
}
return data[++index];
}The next() method in the io.nats.jparse.source.CharArrayCharSource class is used to retrieve the next character from the source data.
Here is a step-by-step description of what this method does based on its body:
- Check if the current index (
index) plus 1 is equal to or greater than the length of thedataarray. - If the condition is true, it means that there are no more characters to read from the source data.
2.1. Set the
indexto the length of thedataarray to indicate that we have reached the end. 2.2. Return the ETX constant, which represents the end-of-transmission character. - If the condition in step 1 is false, it means that there are more characters to read from the source data.
3.1. Increment the
indexby 1. 3.2. Return the character at the newindexin thedataarray.
This method basically keeps track of the current position in the data array and returns the next character each time it is called. If there are no more characters to read, it returns the ETX constant to indicate the end of transmission.

public void checkForJunk()
@Override
public void checkForJunk() {
int index = this.index;
final char[] data = this.data;
final int length = data.length;
int ch = ETX;
for (; index < length; index++) {
ch = data[index];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
continue;
default:
throw new UnexpectedCharacterException("Junk", "Unexpected extra characters", this);
}
}
}The checkForJunk method, defined in the CharArrayCharSource class, is used to check if there are any unexpected extra characters in the data stored in the CharArrayCharSource object.
Here is a step-by-step description of what the method does based on its body:
- It begins by initializing the
indexvariable with the current index of the character being checked in the data. - It then retrieves the data stored in the
CharArrayCharSourceobject and assigns it to thedatavariable. - The length of the data is obtained and stored in the
lengthvariable. - The
chvariable is initialized with the ETX (End of Text) character. ETX typically has a value of 3. - A loop is initiated where
indexis incremented for every iteration until it reaches the length of the data. - Inside the loop, the character at the current index in the data is assigned to the
chvariable. - The
switchstatement is used to perform different actions based on the value ofch. - If
chmatches any of the four white space characters -NEW_LINE_WS,CARRIAGE_RETURN_WS,TAB_WS, orSPACE_WS, the loop continues to the next iteration without executing any further code. - If
chdoes not match any of the white space characters, it means that an unexpected character is found. - In such a case, an
UnexpectedCharacterExceptionis thrown with the message "Junk" and "Unexpected extra characters", along with the currentCharArrayCharSourceobject as an argument. - If the loop completes without throwing an exception, it means that there are no unexpected extra characters in the data.
public int nextSkipWhiteSpace()
@Override
public int nextSkipWhiteSpace() {
int index = this.index + 1;
final char[] data = this.data;
final int length = data.length;
int ch = ETX;
loop: for (; index < length; index++) {
ch = data[index];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
continue;
default:
break loop;
}
}
this.index = index;
return index == length ? ETX : ch;
}The method nextSkipWhiteSpace is defined in the class io.nats.jparse.source.CharArrayCharSource. Here is a step-by-step description of what this method does based on its body:
-
It overrides the method
nextSkipWhiteSpacefrom the superclass. -
It initializes a variable
indexwith the value ofthis.index + 1. -
It retrieves the character array
dataand its length from the class. -
It initializes a variable
chwith the value of ETX (end-of-text character). -
It starts a loop that iterates over the characters in the
dataarray, starting from theindexvalue. -
Inside the loop, it assigns the current character to the variable
ch. -
It uses a switch statement to check the value of
chagainst four possible whitespace characters:NEW_LINE_WS,CARRIAGE_RETURN_WS,TAB_WS, andSPACE_WS. -
If
chmatches any of the whitespace characters, the loop continues to the next iteration without executing the remaining code in the loop body. -
If
chdoes not match any of the whitespace characters, the loop is exited using thebreakstatement with thelooplabel. -
After the loop, the variable
indexis assigned the value of the loop index. -
The method then returns the value of
ch, unlessindexis equals tolength, in which case it returns the value of ETX.
Please note that the values ETX, NEW_LINE_WS, CARRIAGE_RETURN_WS, TAB_WS, and SPACE_WS are not defined in the given code snippet and their meanings may be specific to the context of the code.

public char skipWhiteSpace()
@Override
public char skipWhiteSpace() {
int index = this.index;
final char[] data = this.data;
final int length = data.length;
char ch;
loop: for (; index < length; index++) {
ch = data[index];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
continue;
default:
break loop;
}
}
this.index = index;
return data[index];
}The skipWhiteSpace method in the CharArrayCharSource class is used to skip any white space characters (including new lines, carriage returns, tabs, and spaces) in the character array data.
Here is a step-by-step description of what the method does:
- It starts by getting the current index from the
this.indexvariable and assigning it to a local variableindex. - It also assigns the character array data from the
this.datavariable to a local variabledata. - It gets the length of the character array and assigns it to a local variable
length. - It declares a local variable
chto hold the current character. - It starts a loop that iterates over the character array from the current index
indexup to the length of the character arraylength. - Inside the loop, it assigns the current character at the current index
indexto the variablech. - It uses a switch statement to check if the
chis a white space character (defined asNEW_LINE_WS,CARRIAGE_RETURN_WS,TAB_WS, orSPACE_WS). - If the
chis a white space character, it continues to the next iteration of the loop. - If the
chis not a white space character, it breaks the loop using abreak loopstatement. - After the loop finishes, it updates the index
this.indexto the value of the local variableindex. - Finally, it returns the character
chfound at the indexindexin the character arraydata.
In summary, the skipWhiteSpace method iterates over a character array, starting from the current index, and skips any white space characters until it finds a non-white space character. It then updates the index and returns the non-white space character found.

public String toEncodedStringIfNeeded(int start, int end)
@Override
public String toEncodedStringIfNeeded(int start, int end) {
if (CharArrayUtils.hasEscapeChar(data, start, end)) {
return getEncodedString(start, end);
} else {
return this.getString(start, end);
}
}The toEncodedStringIfNeeded method defined in the CharArrayCharSource class in the io.nats.jparse.source package is responsible for converting a portion of the character array to a string, checking if any escape characters exist within the range.
Here is a step-by-step description of what the method does based on its body:
- The method overrides the
toEncodedStringIfNeededmethod from its parent class. - It takes two parameters,
startandend, which represent the start and end indices of the desired portion of the character array to convert. - The method starts by checking whether the character array within the specified range contains any escape characters using the
CharArrayUtils.hasEscapeCharmethod. - If any escape characters are found, it invokes the
getEncodedStringmethod with the samestartandendindices to return the properly encoded string. - If no escape characters are found within the specified range, it invokes the
getStringmethod with the samestartandendindices to return the string as it is without any encoding. - The method then returns the result of either the encoded or raw string based on the presence of escape characters within the specified range.
public NumberParseResult findEndOfNumberFast()
@Override
public NumberParseResult findEndOfNumberFast() {
int i = index + 1;
char ch = 0;
final char[] data = this.data;
final int length = data.length;
for (; i < length; i++) {
ch = data[i];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
case ATTRIBUTE_SEP:
case ARRAY_SEP:
case OBJECT_END_TOKEN:
case ARRAY_END_TOKEN:
index = i;
return new NumberParseResult(i, false);
case NUM_0:
case NUM_1:
case NUM_2:
case NUM_3:
case NUM_4:
case NUM_5:
case NUM_6:
case NUM_7:
case NUM_8:
case NUM_9:
break;
case DECIMAL_POINT:
index = i;
return findEndOfFloatFast();
case EXPONENT_MARKER:
case EXPONENT_MARKER2:
index = i;
return parseFloatWithExponentFast();
default:
throw new IllegalStateException("Unexpected character " + ch + " at index " + index);
}
}
index = i;
return new NumberParseResult(i, false);
}This method is defined in the class io.nats.jparse.source.CharArrayCharSource and is used to find the end of a number in a character array.
Initialize the variable i to index + 1.
Initialize the variable ch to 0.
Get a reference to the character array data from this.data.
Get the length of the character array and store it in the variable length.
Start a for loop, iterating from i to length.
Inside the loop, get the character at index i and store it in the variable ch.
Use a switch statement to check for various characters:
- If
chis a whitespace character (e.g. newline, carriage return, tab, space) or one of the specified tokens (ATTRIBUTE_SEP,ARRAY_SEP,OBJECT_END_TOKEN,ARRAY_END_TOKEN), update the value ofindextoiand return a newNumberParseResultwith the updated index andfalseas the boolean value. - If
chis any of the digits (NUM_0,NUM_1,NUM_2,NUM_3,NUM_4,NUM_5,NUM_6,NUM_7,NUM_8,NUM_9), continue to the next iteration. - If
chis a decimal point (DECIMAL_POINT), update the value ofindextoiand return the result of calling the methodfindEndOfFloatFast(). - If
chis an exponent marker (EXPONENT_MARKERorEXPONENT_MARKER2), update the value ofindextoiand return the result of calling the methodparseFloatWithExponentFast(). - If none of the above conditions match, throw an
IllegalStateExceptionwith the message "Unexpected character" followed bychand the current value ofindex.
After the loop ends, update the value of index to i.
Finally, return a new NumberParseResult with i as the index and false as the boolean value.

private NumberParseResult findEndOfFloatFast() {
int i = index + 1;
char ch = 0;
final char[] data = this.data;
final int length = data.length;
for (; i < length; i++) {
ch = data[i];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
case ATTRIBUTE_SEP:
case ARRAY_SEP:
case OBJECT_END_TOKEN:
case ARRAY_END_TOKEN:
index = i;
return new NumberParseResult(i, true);
case NUM_0:
case NUM_1:
case NUM_2:
case NUM_3:
case NUM_4:
case NUM_5:
case NUM_6:
case NUM_7:
case NUM_8:
case NUM_9:
break;
case EXPONENT_MARKER:
case EXPONENT_MARKER2:
index = i;
return parseFloatWithExponentFast();
default:
throw new UnexpectedCharacterException("Parsing JSON Float Number", "Unexpected character", this, ch, i);
}
}
index = i;
return new NumberParseResult(i, true);
}The method findEndOfFloatFast in class io.nats.jparse.source.CharArrayCharSource is used to find the end of a floating-point number in a character array. It returns a NumberParseResult object which contains the position of the end of the floating-point number and a flag indicating if the parsing was successful.
Here is a step-by-step description of what the method does:
- Initialize a local variable
itoindex + 1, whereindexis an instance variable representing the current position in the character array. - Initialize a local variable
chto 0. - Get a reference to the character array
datafrom thethisobject, which refers to the current instance ofCharArrayCharSource. - Get the length of the character array and store it in a local variable
length. - Start a
forloop, iterating over the characters in the character array starting fromiand going up tolength - 1. - Inside the loop, get the current character at index
iand store it in the variablech. - Use a
switchstatement to check the value ofchagainst various cases:- If
chis equal to any of the whitespace characters (NEW_LINE_WS,CARRIAGE_RETURN_WS,TAB_WS,SPACE_WS) or any of the JSON delimiters (ATTRIBUTE_SEP,ARRAY_SEP,OBJECT_END_TOKEN,ARRAY_END_TOKEN), then update theindexvariable toiand return a newNumberParseResultobject with the current positioniandtrueas the flag. - If
chis any of the digit characters (NUM_0toNUM_9), continue to the next iteration of the loop. - If
chis either the exponent marker character (EXPONENT_MARKER) or the second exponent marker character (EXPONENT_MARKER2), update theindexvariable toiand return the result of calling theparseFloatWithExponentFastmethod. - If none of the above cases match, throw an
UnexpectedCharacterExceptionwith the message "Parsing JSON Float Number", "Unexpected character", the current instance ofCharArrayCharSource, the unexpected characterch, and the current positioni.
- If
- After the
forloop finishes, update theindexvariable toiand return a newNumberParseResultobject with the current positioniandtrueas the flag.
private NumberParseResult parseFloatWithExponentFast() {
int i = index + 1;
char ch = 0;
int signOperator = 0;
final char[] data = this.data;
final int length = data.length;
for (; i < length; i++) {
ch = data[i];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
case ATTRIBUTE_SEP:
case ARRAY_SEP:
case OBJECT_END_TOKEN:
case ARRAY_END_TOKEN:
index = i;
return new NumberParseResult(i, true);
case MINUS:
case PLUS:
signOperator++;
if (signOperator > 1) {
throw new IllegalStateException("Too many sign operators when parsing exponent of float");
}
break;
case NUM_0:
case NUM_1:
case NUM_2:
case NUM_3:
case NUM_4:
case NUM_5:
case NUM_6:
case NUM_7:
case NUM_8:
case NUM_9:
break;
default:
throw new IllegalStateException("Unexpected character " + ch + " at index " + index);
}
}
index = i;
return new NumberParseResult(i, true);
}The method parseFloatWithExponentFast is defined in the class io.nats.jparse.source.CharArrayCharSource and returns a NumberParseResult.
Here is a step by step description of what the method is doing:
- Initialize the variable
iwith the valueindex + 1. - Initialize the variable
chwith the value0. - Initialize the variable
signOperatorwith the value0. - Get the character array
datafrom the objectthisand assign it to the variabledata. - Get the length of the character array
dataand assign it to the variablelength. - Start a loop that iterates from the value of
ito the length ofdata.- Assign the current character of
dataat indexito the variablech. - Use a switch statement to check the value of
chagainst various cases:- If
chis equal to any of the following characters:NEW_LINE_WS,CARRIAGE_RETURN_WS,TAB_WS,SPACE_WS,ATTRIBUTE_SEP,ARRAY_SEP,OBJECT_END_TOKEN, orARRAY_END_TOKEN, setindextoiand return a newNumberParseResultobject with the value ofiandtrue. - If
chis equal toMINUSorPLUS, incrementsignOperatorby 1. IfsignOperatoris greater than 1, throw anIllegalStateExceptionwith the message "Too many sign operators when parsing exponent of float". - If
chis any of the digits fromNUM_0toNUM_9, continue to the next iteration. - If none of the above cases match, throw an
IllegalStateExceptionwith the message "Unexpected character" followed by the value ofchand "at index" followed by the value ofindex.
- If
- Assign the current character of
- After the loop ends, set
indextoiand return a newNumberParseResultobject with the value ofiandtrue.
public int findEndOfEncodedStringFast()
@Override
public int findEndOfEncodedStringFast() {
int i = ++index;
final char[] data = this.data;
final int length = data.length;
boolean controlChar = false;
for (; i < length; i++) {
char ch = data[i];
switch(ch) {
case CONTROL_ESCAPE_TOKEN:
controlChar = !controlChar;
continue;
case STRING_END_TOKEN:
if (!controlChar) {
index = i + 1;
return i;
}
controlChar = false;
break;
default:
controlChar = false;
break;
}
}
throw new IllegalStateException("Unable to find closing for String");
}The findEndOfEncodedStringFast method in the io.nats.jparse.source.CharArrayCharSource class is used to find the index of the closing delimiter of an encoded string. Here is a step-by-step description of what this method does:
- Initialize
iwith the incrementedindexvalue. This will be the starting index for searching the encoding string. - Get the character array
datafrom the source object. - Get the length of the character array.
- Initialize a boolean variable
controlChartofalse. This variable is used to keep track of whether a control character was encountered. - Start a loop from
itolength - 1. This loop iterates over each character in the character array. - Get the character
chat indexi. - Check the value of
chusing a switch statement to handle different cases:- If
chis equal to theCONTROL_ESCAPE_TOKEN, toggle the value ofcontrolChar(i.e., change it fromtruetofalseor vice versa). - If
chis equal to theSTRING_END_TOKENandcontrolCharisfalse, update theindextoi + 1and returni. This denotes that the end of the encoding string has been found. - If
chis anything else, setcontrolChartofalse.
- If
- If no end of the encoding string is found, throw an
IllegalStateExceptionwith the message "Unable to find closing for String".
Overall, this method iterates over the characters in the input character array starting from the given index and looks for the closing delimiter of an encoded string. It handles control characters and ensures that the closing delimiter is not escaped before returning the index of the closing delimiter. If the closing delimiter is not found, it throws an exception to indicate the error.

private int findEndOfStringControlEncode(int i) {
final char[] data = this.data;
final int length = data.length;
char ch = 0;
ch = data[i];
switch(ch) {
case CONTROL_ESCAPE_TOKEN:
case STRING_END_TOKEN:
case 'n':
case 'b':
case '/':
case 'r':
case 't':
case 'f':
return i;
case 'u':
return findEndOfHexEncoding(i);
default:
throw new UnexpectedCharacterException("Parsing JSON String", "Unexpected character while finding closing for String", this, ch, i);
}
}This method is used to find the index of the closing character for a JSON string when the starting character is a control or escape character.
-
i: Index of the starting character in thedataarray.
- Get the reference to the
dataarray and the length of the array. - Initialize a
charvariablechto 0. - Assign the value of the character at index
iin thedataarray to thechvariable. - Perform a switch-case check on the value of
ch:- If
chis equal toCONTROL_ESCAPE_TOKEN,STRING_END_TOKEN,'n','b','/','r','t', or'f', return the current indexi. - If
chis equal to'u', call thefindEndOfHexEncodingmethod and return its result. - If
chdoes not match any of the above cases, throw anUnexpectedCharacterExceptionwith appropriate error message, indicating an unexpected character while finding the closing character for the JSON string.
- If
- The index of the closing character for the JSON string.
Note: The actual values for CONTROL_ESCAPE_TOKEN and STRING_END_TOKEN are not provided in the given code snippet

public int findEndOfEncodedString()
@Override
public int findEndOfEncodedString() {
int i = ++index;
final char[] data = this.data;
final int length = data.length;
char ch = 0;
for (; i < length; i++) {
ch = data[i];
switch(ch) {
case CONTROL_ESCAPE_TOKEN:
i = findEndOfStringControlEncode(i + 1);
continue;
case STRING_END_TOKEN:
index = i + 1;
return i;
default:
if (ch >= SPACE_WS) {
continue;
}
throw new UnexpectedCharacterException("Parsing JSON String", "Unexpected character while finding closing for String", this, ch, i);
}
}
throw new UnexpectedCharacterException("Parsing JSON Encoded String", "Unable to find closing for String", this, ch, i);
}The findEndOfEncodedString method is defined in the io.nats.jparse.source.CharArrayCharSource class. It overrides the findEndOfEncodedString method from its parent class.
Here is a step-by-step description of what the method is doing:
- The
indexvariable is incremented by 1 and stored in theivariable. - The
datachar array from the parent class is assigned to thedatavariable. - The length of the
dataarray is stored in thelengthvariable. - A variable
chis initialized to the value0. - A
forloop is started, iterating fromitolength. - In each iteration, the value at the current index
iin thedataarray is stored in thechvariable. - A
switchstatement is used to check the value ofch. - If
chis equal toCONTROL_ESCAPE_TOKEN, then thefindEndOfStringControlEncodemethod is called with the argumenti + 1. The returned value is then assigned back toi, and the next iteration of the loop is started. - If
chis equal toSTRING_END_TOKEN, thenindexis updated toi + 1, and the current value ofiis returned. - If
chis none of the above, it checks ifchis greater than or equal toSPACE_WS.- If it is, the loop continues to the next iteration.
- If it is not, an
UnexpectedCharacterExceptionis thrown with a message stating the unexpected character, the currentCharSource,ch, and the indexi.
- If the loop completes without finding a closing for a string, an
UnexpectedCharacterExceptionis thrown with a message stating the inability to find a closing for the string, the currentCharSource, the last value ofch, and the last value ofi.
This method is used to find the end of an encoded string in the JSON input. It iterates through the characters starting from the index position and looks for the closing token of the string or any control escape tokens. If a closing token is found, it updates the index and returns the position of the closing token. If a control escape token is found, it delegates the further handling to the findEndOfStringControlEncode method. If none of these conditions are met, it throws an exception indicating an unexpected character. If the loop completes without finding a closing token, it throws an exception indicating the inability to find a closing for the string.

private int findEndOfHexEncoding(int index) {
final char[] data = this.data;
final int length = data.length;
if (isHex(data[++index]) && isHex(data[++index]) && isHex(data[++index]) && isHex(data[++index])) {
return index;
} else {
throw new UnexpectedCharacterException("Parsing hex encoding in a string", "Unexpected character", this);
}
}The method findEndOfHexEncoding in the class io.nats.jparse.source.CharArrayCharSource is used to find the end of a hex encoding in a string. Here is a step-by-step description of what the method is doing:
-
It takes an input parameter
indexwhich represents the current position in the character array. -
It initializes a local variable
datawith the character arraythis.dataandlengthwith the length of the character array. -
It checks if the character at position
index + 1,index + 2,index + 3, andindex + 4in thedataarray are valid hexadecimal characters by calling the methodisHex(). -
If all four characters are valid hex characters, the method returns the current
indexvalue. -
If any of the characters is not a valid hex character, the method throws an exception of type
UnexpectedCharacterExceptionwith the error message "Unexpected character" and a reference to thethisobject.
In summary, the findEndOfHexEncoding method iterates over the characters in the data array starting from the index position and checks if the next four characters form a valid hex encoding. If they do, it returns the index of the last character in the encoding. If any of the characters is not valid, it throws an exception.

private boolean isHex(char datum) {
switch(datum) {
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return true;
default:
return false;
}
}The method isHex in the class io.nats.jparse.source.CharArrayCharSource is used to check if a given character is a hex digit.
Here is the step-by-step description of what the method is doing based on its body:
- Define a private boolean method named
isHexthat takes a character as input. - The method uses a switch-case statement to handle different cases of the
datumcharacter. - In the switch statement, each case represents a valid hex digit character. The valid hex digit characters are: 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', and '9'.
- If the
datumcharacter matches any of the valid hex digit characters, the method returnstrue. - If the
datumcharacter does not match any of the valid hex digit characters, the method returnsfalse. - The method is private, which means it can only be accessed within the
io.nats.jparse.source.CharArrayCharSourceclass.
That's the step-by-step description of the isHex method. It checks whether a given character is a valid hex digit character.

public int findAttributeEnd()
@Override
public int findAttributeEnd() {
int index = this.index;
final char[] data = this.data;
final int length = this.data.length;
loop: for (; index < length; index++) {
char ch = data[index];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
case ATTRIBUTE_SEP:
this.index = index;
break loop;
}
}
return index;
}The method findAttributeEnd in the class io.nats.jparse.source.CharArrayCharSource is used to find the end of an attribute within a character array.
Here are the steps performed by this method:
-
The method overrides the
findAttributeEndmethod, ensuring that it has the same signature as the overridden method in the parent class. -
The method first initializes a local variable
indexwith the value ofthis.index.this.indexrefers to the current index within the character array. -
The method then assigns the character array
datafrom the class instance to a local variabledata. -
It also assigns the length of the character array
datato a local variablelength. -
The method has a loop that iterates from the current index
indexto the length of the character arraydata. -
Inside the loop, it retrieves the character
chat the current indexindexfrom the character arraydata. -
It then checks the character
chagainst several predefined whitespace characters, likeNEW_LINE_WS,CARRIAGE_RETURN_WS,TAB_WS,SPACE_WS, andATTRIBUTE_SEP. -
If the character
chmatches any of these whitespace characters, it updates thethis.indexto the current indexindexand breaks the loop using a labeledbreakstatement. -
After the loop ends, the method returns the value of
index.
To summarize, the findAttributeEnd method scans through the character array data starting from the current index this.index until it finds a whitespace character. It then returns the index where the whitespace character was found, indicating the end of the attribute.

public boolean findChar(char c)
@Override
public boolean findChar(char c) {
int index = this.index;
final char[] data = this.data;
final int length = this.data.length;
for (; index < length; index++) {
if (data[index] == c) {
this.index = index;
return true;
}
}
return false;
}The findChar method in the CharArrayCharSource class is used to find a specific character in a character array.
Here is a step-by-step description of what the method is doing:
-
The method overrides the
findCharmethod declared in the superinterface or superclass. -
The
this.indexvariable is assigned to a local variable calledindex. This is done for efficiency purposes as retrieving the instance variable directly multiple times may be costly. -
The
this.datavariable, which represents the character array being searched, is assigned to a local variable calleddata. -
The
lengthvariable is assigned the length of thedatacharacter array. -
A
forloop is started withindexbeing the starting point of the loop andlengthbeing the end condition. -
Inside the loop, the current character at the
indexposition of thedataarray is compared to the charactercthat is being searched for. -
If the characters match, the
this.indexinstance variable is updated with the currentindexvalue, and the method returnstrueindicating that the character was found. -
If the loop completes without finding a matching character, the method returns
falseindicating that the character was not found in the array.
Please note that this step-by-step description assumes that the instance variables (this.index, this.data, etc.) are properly initialized before using the findChar method.

public int findEndString()
@Override
public int findEndString() {
int i = ++index;
final char[] data = this.data;
final int length = data.length;
char ch = 0;
for (; i < length; i++) {
ch = data[i];
switch(ch) {
case STRING_END_TOKEN:
index = i;
return i;
default:
if (ch >= SPACE_WS) {
continue;
}
throw new UnexpectedCharacterException("Parsing JSON String", "Unexpected character while finding closing for String", this, ch, i);
}
}
throw new UnexpectedCharacterException("Parsing JSON String", "Unable to find closing for String", this, ch, i);
}The findEndString method in the CharArrayCharSource class is used to find the end of a JSON string within a given character array.
Here is a step-by-step description of what the method is doing:
- Increment the
indexby 1 and assign it to a local variablei. - Retrieve the character array
datafrom the currentCharArrayCharSourceobject. - Get the length of the character array and assign it to a local variable
length. - Initialize a variable
chwith a value of 0. - Start a loop from the current
index(i) until the end of the character array. - Within the loop, retrieve the character at position
ifrom the character array and assign it toch. - Use a switch statement to check the value of
ch.- If
chis equal to a constant variableSTRING_END_TOKEN, update theindexwith the current value ofiand returnias the index of the end of the string. - If
chis not equal toSTRING_END_TOKEN, check ifchis greater than or equal to a constant variableSPACE_WS(a whitespace character).- If it is greater than or equal to
SPACE_WS, continue to the next iteration of the loop. - If it is not greater than or equal to
SPACE_WS, throw anUnexpectedCharacterExceptionwith a message indicating that an unexpected character was found while finding the closing for the string.
- If it is greater than or equal to
- If
- If the end of the character array is reached without finding the closing for the string, throw an
UnexpectedCharacterExceptionwith a message indicating that the closing for the string was not found.
In summary, this method iterates over the character array starting from the current index, looking for the end of a JSON string. If the end of the string is found, the method returns the index of the closing character. If an unexpected character is encountered, an exception is thrown. If the closing for the string is not found, an exception is also thrown.

public NumberParseResult findEndOfNumber()
@Override
public NumberParseResult findEndOfNumber() {
final char startCh = getCurrentChar();
final int startIndex = index;
char ch = startCh;
int i = index + 1;
final char[] data = this.data;
final int length = data.length;
loop: for (; i < length; i++) {
ch = data[i];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
case ATTRIBUTE_SEP:
case ARRAY_SEP:
case OBJECT_END_TOKEN:
case ARRAY_END_TOKEN:
break loop;
case NUM_0:
case NUM_1:
case NUM_2:
case NUM_3:
case NUM_4:
case NUM_5:
case NUM_6:
case NUM_7:
case NUM_8:
case NUM_9:
break;
case DECIMAL_POINT:
if (startCh == MINUS) {
final int numLenSoFar = i - startIndex;
if (numLenSoFar == 1) {
throw new UnexpectedCharacterException("Parsing JSON Number", "Unexpected character", this, ch, i);
}
}
index = i;
return findEndOfFloat();
case EXPONENT_MARKER:
case EXPONENT_MARKER2:
index = i;
return parseFloatWithExponent();
default:
throw new UnexpectedCharacterException("Parsing JSON Number", "Unexpected character", this, ch, i);
}
}
index = i;
final int numLength = i - startIndex;
switch(startCh) {
case NUM_0:
if (numLength != 1) {
throw new UnexpectedCharacterException("Parsing JSON Int Number", "Int can't start with a 0 ", this, startCh, startIndex);
}
break;
case PLUS:
throw new UnexpectedCharacterException("Parsing JSON Int Number", "Int can't start with a plus ", this, startCh, startIndex);
case MINUS:
switch(numLength) {
case 1:
throw new UnexpectedCharacterException("Parsing JSON Int Number", "Int can't be only a minus, number is missing", this, startCh, startIndex);
case 2:
break;
default:
if (data[startIndex + 1] == NUM_0) {
throw new UnexpectedCharacterException("Parsing JSON Int Number", "0 can't be after minus sign", this, startCh, startIndex);
}
}
}
return new NumberParseResult(i, false);
}The findEndOfNumber method is defined in the io.nats.jparse.source.CharArrayCharSource class. This method is used to find the end index of a number in a character array source.
Here is a step-by-step description of what the method is doing:
- It starts by getting the current character from the character array source (
getCurrentChar()). - It initializes the
startChvariable with the current character and thestartIndexvariable with the current index. - It then enters a loop starting from
i = index + 1untili < length(wherelengthis the length of the character array). - Inside the loop, it assigns the next character (
data[i]) to thechvariable. - It then performs a switch case on the
chvariable to check for various characters and perform different actions:- If the character is one of the whitespace characters (
NEW_LINE_WS,CARRIAGE_RETURN_WS,TAB_WS,SPACE_WS), one of the separators (ATTRIBUTE_SEP,ARRAY_SEP), or one of the end tokens (OBJECT_END_TOKEN,ARRAY_END_TOKEN), it breaks out of the loop. - If the character is one of the digits (
NUM_0toNUM_9), it continues to the next iteration of the loop. - If the character is a decimal point (
DECIMAL_POINT), it checks if thestartChis a minus sign (MINUS). If it is, it throws an exception if the length of the number so far is 1. It then sets theindextoiand returns the result of calling thefindEndOfFloatmethod. - If the character is an exponent marker (
EXPONENT_MARKERorEXPONENT_MARKER2), it sets theindextoiand returns the result of calling theparseFloatWithExponentmethod. - If none of the above cases match, it throws an exception for an unexpected character.
- If the character is one of the whitespace characters (
- After the loop, it sets the
indextoi(the current index) and calculates the length of the number (numLength) by subtracting thestartIndexfromi. - It then performs a switch case on the
startChvariable to check for different cases:- If the
startChisNUM_0and the length of the number is not 1, it throws an exception for an integer number starting with 0. - If the
startChis a plus sign (PLUS), it throws an exception for an integer number starting with a plus sign. - If the
startChis a minus sign (MINUS), it checks the length of the number:- If the length is 1, it throws an exception for a minus sign without a number.
- If the length is 2, it continues to the next step.
- If the length is greater than 2 and the character after the minus sign is
NUM_0, it throws an exception for 0 being after a minus sign.
- If the
- Finally, it returns a new
NumberParseResultobject with the end index (i) and a boolean indicating whether the number is a float (false).
private NumberParseResult findEndOfFloat() {
int i = index + 1;
char ch = (char) next();
if (!isNumber(ch)) {
throw new UnexpectedCharacterException("Parsing float part of number", "After decimal point expecting number but got", this, ch, this.index);
}
final char[] data = this.data;
final int length = data.length;
for (; i < length; i++) {
ch = data[i];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
case ATTRIBUTE_SEP:
case ARRAY_SEP:
case OBJECT_END_TOKEN:
case ARRAY_END_TOKEN:
index = i;
return new NumberParseResult(i, true);
case NUM_0:
case NUM_1:
case NUM_2:
case NUM_3:
case NUM_4:
case NUM_5:
case NUM_6:
case NUM_7:
case NUM_8:
case NUM_9:
break;
case EXPONENT_MARKER:
case EXPONENT_MARKER2:
index = i;
return parseFloatWithExponent();
default:
throw new UnexpectedCharacterException("Parsing JSON Float Number", "Unexpected character", this, ch, i);
}
}
index = i;
return new NumberParseResult(i, true);
}The findEndOfFloat method is a private method defined in the io.nats.jparse.source.CharArrayCharSource class. It is responsible for finding the end of a floating-point number within a JSON string.
Here is a step-by-step description of what the method does based on its body:
-
The method starts by initializing a local variable
iwith the value ofindex + 1. -
It then retrieves the next character
chfrom the input stream by calling thenext()method. -
It checks if
chis a valid number character by calling theisNumber()method. If it is not a valid number character, it throws anUnexpectedCharacterExceptionwith an appropriate error message. -
Next, the method accesses the
dataarray andlengthof the array from the parent object. -
It enters a
forloop that iterates fromitolength-1. -
Inside the loop, it gets the character
chat the current indexifrom thedataarray. -
It then performs a
switchstatement onchto handle different types of characters:-
If
chis one of the whitespace characters or special tokens (e.g., newline, tab, comma, array or object end token), it sets theindextoiand returns a newNumberParseResultobject with the current index andtruevalue indicating that the float number has been successfully parsed. -
If
chis one of the numeric digits (0-9), it continues the loop without performing any action. -
If
chis an exponent marker (e.g., 'E' or 'e'), it sets theindextoiand calls theparseFloatWithExponentmethod to handle parsing of the floating-point number with an exponent. -
If
chis any other character, it throws anUnexpectedCharacterExceptionwith an appropriate error message.
-
-
After the loop, it sets the
indextoiand returns a newNumberParseResultobject with the current index andtruevalue indicating that the float number has been successfully parsed.
In summary, the findEndOfFloat method iterates through the characters of the input string starting from the index + 1 position. It checks each character to determine if it is a valid part of a floating-point number, until it reaches a character that is not part of the number. It returns the index of the last character of the number and whether or not the number was successfully parsed.

private boolean isNumber(final char ch) {
switch(ch) {
case NUM_0:
case NUM_1:
case NUM_2:
case NUM_3:
case NUM_4:
case NUM_5:
case NUM_6:
case NUM_7:
case NUM_8:
case NUM_9:
return true;
default:
return false;
}
}The isNumber method is defined within the io.nats.jparse.source.CharArrayCharSource class. It determines whether a given character is a number or not.
- Type:
char - Description: The character that needs to be checked.
- The method takes a character
chas input. - It uses a switch statement to compare the input character with a set of predefined constants representing the digits 0 to 9.
- If the input character matches any of the predefined constants, the method returns
true, indicating that the character is a number. - If the input character does not match any of the predefined constants, the method returns
false, indicating that the character is not a number.
private NumberParseResult parseFloatWithExponent() {
char ch = (char) next();
if (!isNumberOrSign(ch)) {
throw new UnexpectedCharacterException("Parsing exponent part of float", "After exponent expecting number or sign but got", this, ch, this.index);
}
if (isSign(ch)) {
ch = (char) next();
if (!isNumber(ch)) {
throw new UnexpectedCharacterException("Parsing exponent part of float after sign", "After sign expecting number but got", this, ch, this.index);
}
}
int i = index + 1;
final char[] data = this.data;
final int length = data.length;
for (; i < length; i++) {
ch = data[i];
switch(ch) {
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
case ATTRIBUTE_SEP:
case ARRAY_SEP:
case OBJECT_END_TOKEN:
case ARRAY_END_TOKEN:
index = i;
return new NumberParseResult(i, true);
case NUM_0:
case NUM_1:
case NUM_2:
case NUM_3:
case NUM_4:
case NUM_5:
case NUM_6:
case NUM_7:
case NUM_8:
case NUM_9:
break;
default:
throw new UnexpectedCharacterException("Parsing Float with exponent", "Unable to find closing for Number", this, ch, i);
}
}
index = i;
return new NumberParseResult(i, true);
}The method parseFloatWithExponent() in class io.nats.jparse.source.CharArrayCharSource is used to parse a floating-point number with an exponent.
Here is a step-by-step description of what the method does based on its body:
- It retrieves the next character from the input and assigns it to the variable
ch. - It checks if the character
chis a number or a sign. If it is not, it throws anUnexpectedCharacterExceptionwith an error message indicating that it was expecting a number or sign. - If the character
chis a sign, it retrieves the next character from the input and assigns it toch. Then, it checks ifchis a number. If it is not, it throws anUnexpectedCharacterExceptionwith an error message indicating that it was expecting a number after the sign. - It initializes an integer variable
iwithindex + 1. This will be used to iterate through the characters in the data array. - It retrieves the data array and its length and assigns them to
dataandlengthvariables respectively. - It enters a loop that starts at
iand iterates untilireaches the end of the data array. - Inside the loop, it assigns the current character at index
itoch. - It then checks the value of
chagainst a set of characters representing whitespace, separators, and the end of objects/arrays. If a match is found, it updates the value ofindextoiand returns a newNumberParseResultobject with the current index and a flag indicating successful parsing. - If
chis a digit (0-9), it continues to the next iteration of the loop. - If
chdoes not match any of the previous cases, it throws anUnexpectedCharacterExceptionwith an error message indicating that it was unable to find a closing character for the number. - After the loop ends, it updates the value of
indextoiand returns a newNumberParseResultobject with the current index and a flag indicating successful parsing.
private boolean isNumberOrSign(char ch) {
switch(ch) {
case NUM_0:
case NUM_1:
case NUM_2:
case NUM_3:
case NUM_4:
case NUM_5:
case NUM_6:
case NUM_7:
case NUM_8:
case NUM_9:
case MINUS:
case PLUS:
return true;
default:
return false;
}
}Method: isNumberOrSign
This method is defined in the io.nats.jparse.source.CharArrayCharSource class and is used to determine if a given character is either a number or a sign (+ or -).
Algorithm:
- Accept a character
chas input. - Perform a switch case on the character
ch. - Check if
chmatches any of the following cases:- If
chis equal to the character constantNUM_0 - If
chis equal to the character constantNUM_1 - If
chis equal to the character constantNUM_2 - If
chis equal to the character constantNUM_3 - If
chis equal to the character constantNUM_4 - If
chis equal to the character constantNUM_5 - If
chis equal to the character constantNUM_6 - If
chis equal to the character constantNUM_7 - If
chis equal to the character constantNUM_8 - If
chis equal to the character constantNUM_9 - If
chis equal to the character constantMINUS - If
chis equal to the character constantPLUS
- If
- If
chmatches any of the above cases, returntrue. - If
chdoes not match any of the above cases, returnfalse.
private boolean isSign(char ch) {
switch(ch) {
case MINUS:
case PLUS:
return true;
default:
return false;
}
}The isSign method in the CharArrayCharSource class is used to determine if a given character is a sign symbol.
Here is a step-by-step description of what the method does:
- The method takes a single character (
ch) as input. - It uses a switch statement to check the value of
ch. - If the value of
chis equal to the constantMINUS, which represents a minus sign, or the constantPLUS, which represents a plus sign, it returnstrue. - If the value of
chdoes not match any of the cases in the switch statement, it returnsfalse.
In summary, the isSign method checks if a given character is a sign symbol (minus or plus) and returns true if it is or false if it isn't.

public int findFalseEnd()
@Override
public int findFalseEnd() {
if (this.data[++index] == 'a' && this.data[++index] == 'l' && this.data[++index] == 's' && this.data[++index] == 'e') {
return ++index;
} else {
throw new UnexpectedCharacterException("Parsing JSON False Boolean", "Unexpected character", this);
}
}The findFalseEnd method defined in the CharArrayCharSource class, located at io.nats.jparse.source.CharArrayCharSource, performs the following steps:
- The method overrides the
findFalseEndmethod, which is declared in a superclass. - It starts by checking if the character at the next index (
++index) in thedataarray is equal to the character'a'. - If the above condition is true, it also checks if the character at the next index is
'l','s', and'e'respectively. - If all the characters
'a','l','s', and'e'are found consecutively, it returns the incremented index value. - If any of the characters are not found consecutively, it throws an
UnexpectedCharacterException. - The
UnexpectedCharacterExceptiontakes the following parameters:"Parsing JSON False Boolean"as the error message,"Unexpected character"as the detailed error description, and the currentCharArrayCharSourceinstance (this) where the exception occurred.
Please note that the ++index operator increments the index value and returns the incremented value.

public int findTrueEnd()
@Override
public int findTrueEnd() {
if (this.data[++index] == 'r' && this.data[++index] == 'u' && this.data[++index] == 'e') {
return ++index;
} else {
throw new UnexpectedCharacterException("Parsing JSON True Boolean", "Unexpected character", this);
}
}The findTrueEnd method in the io.nats.jparse.source.CharArrayCharSource class is used to determine the end position of the "true" boolean value in a JSON document.
Here is a step-by-step breakdown of how the method works:
- The method overrides the
findTrueEndmethod defined in the superclass. - The method begins by incrementing the
indexvariable using the++indexsyntax. - It then checks if the character at the current
indexin thedataarray is equal to the character 'r'. - If it is, the method proceeds to the next step.
- The method then increments the
indexvariable again and checks if the character at the newindexis equal to the character 'u'. - If it is, the method proceeds to the next step.
- The method increments the
indexvariable once more and checks if the character at the newindexis equal to the character 'e'. - If it is, the method increments the
indexagain and returns the newindexvalue. - If any of the checks made in steps 3, 5, or 7 fail, it means that there is an unexpected character in the input, and the method throws an
UnexpectedCharacterException. - The
UnexpectedCharacterExceptionis constructed with a message indicating that it occurred while parsing a JSON True Boolean and providing the information about the unexpected character and the current source. - The exception is thrown, and the execution of the method is stopped.
This findTrueEnd method allows the caller to locate the true boolean value in a JSON document and determine its end position.

public boolean findObjectEndOrAttributeSep()
@Override
public boolean findObjectEndOrAttributeSep() {
int i = index;
char ch = 0;
final char[] data = this.data;
final int length = data.length;
for (; i < length; i++) {
ch = data[i];
switch(ch) {
case OBJECT_END_TOKEN:
this.index = i + 1;
return true;
case ATTRIBUTE_SEP:
this.index = i;
return false;
}
}
throw new UnexpectedCharacterException("Parsing Object Key", "Finding object end or separator", this);
}The method findObjectEndOrAttributeSep in the class io.nats.jparse.source.CharArrayCharSource is used to search for either the end of an object or an attribute separator in a character array.
Here is a step-by-step description of what this method is doing:
- Set the initial value of the variable
ito the current index value. - Set the initial value of the variable
chto zero. - Get the reference to the character array
dataand the length of the array. - Start a loop to iterate through the elements of the character array, starting from the current index
iand ending at the last element of the array. - Within the loop, assign the current element of the character array to the variable
ch. - Use a switch statement to check the value of
chagainst two possible cases: a. Ifchmatches the constantOBJECT_END_TOKEN, update the current indexindextoi + 1and returntrueto indicate that the end of an object has been found. b. Ifchmatches the constantATTRIBUTE_SEP, update the current indexindextoiand returnfalseto indicate that an attribute separator has been found. - If none of the above cases match for any element of the character array, throw an
UnexpectedCharacterExceptionwith a detailed message indicating that the method was trying to parse an object key, while searching for either the object end or separator. - End of the loop.
In summary, the method iterates through the character array data starting from the current index index and checks if each character matches either the object end token or the attribute separator. If a match is found, it updates the current index and returns a boolean value indicating the result. If no match is found, it throws an exception.

public boolean findCommaOrEndForArray()
@Override
public boolean findCommaOrEndForArray() {
int i = index;
char ch = 0;
final char[] data = this.data;
final int length = data.length;
for (; i < length; i++) {
ch = data[i];
switch(ch) {
case ARRAY_END_TOKEN:
this.index = i + 1;
return true;
case ARRAY_SEP:
this.index = i;
return false;
case NEW_LINE_WS:
case CARRIAGE_RETURN_WS:
case TAB_WS:
case SPACE_WS:
continue;
default:
throw new UnexpectedCharacterException("Parsing Object Key", "Finding object end or separator", this, ch, i);
}
}
throw new UnexpectedCharacterException("Parsing Array", "Finding list end or separator", this);
}The findCommaOrEndForArray method in the CharArrayCharSource class is used to find the comma or end token within an array. Here is a step-by-step description of what the method does:
- Start at the current index stored in the
indexvariable. - Initialize a temporary variable
chto store the current character being examined. - Get the character array
datafrom the instance variablethis.data. - Get the length of the character array in the
lengthvariable. - Start a loop that iterates from the current index (
i) to the length of the character array. - Get the character at the current index (
i) and store it in thechvariable. - Use a switch statement to check the value of
ch. - If the character is equal to the
ARRAY_END_TOKEN, set theindexvariable toi + 1, indicating that the end of the array has been found. Then, returntrueto indicate that the end token has been found. - If the character is equal to the
ARRAY_SEP, set theindexvariable toi, indicating that a comma separator has been found. Then, returnfalseto indicate that a separator has been found. - If the character is one of the defined whitespace characters (
NEW_LINE_WS,CARRIAGE_RETURN_WS,TAB_WS,SPACE_WS), skip the current iteration of the loop and continue to the next character. - If the character does not match any of the expected values, throw an
UnexpectedCharacterExceptionwith the appropriate error message and include information about the current character and its index. - If the end of the array is reached without finding an end token or separator, throw an
UnexpectedCharacterExceptionwith the appropriate error message and context information about the parsing operation.
This method is used to parse an input character array and determine whether the next character is an end token or a separator within an array, based on the defined array tokens and whitespace characters. It returns a boolean value indicating whether an end token has been found or not.

public int findNullEnd()
@Override
public int findNullEnd() {
if (this.data[++index] == 'u' && this.data[++index] == 'l' && this.data[++index] == 'l') {
return ++index;
} else {
throw new UnexpectedCharacterException("Parsing JSON Null", "Unexpected character", this);
}
}The findNullEnd method in the CharArrayCharSource class is used to find the end position of a "null" value in a JSON string.
Here is a step-by-step description of what the method does:
-
The method overrides the
findNullEndmethod defined in the superclass, indicating that it provides a specific implementation for this method. -
The method begins by incrementing the value of the
indexvariable by 1. This is done using the pre-increment operator++before theindexvariable. This means that the new value ofindexwill be one greater than its previous value. -
The method then checks if the character at the new
indexposition in thedataarray is equal to the character 'u'. If it is, the condition is true and the code block inside the if statement is executed. -
Inside the if statement, the value of
indexis again incremented by 1 using the pre-increment operator. This means that the new value ofindexwill be one greater than its previous value. -
The method then checks if the character at the new
indexposition in thedataarray is equal to the character 'l'. If it is, the condition is true and the code block inside the if statement is executed. -
Inside the if statement, the value of
indexis again incremented by 1 using the pre-increment operator. This means that the new value ofindexwill be one greater than its previous value. -
The method then checks if the character at the new
indexposition in thedataarray is equal to the character 'l'. If it is, the condition is true and the code block inside the if statement is executed. -
Inside the if statement, the value of
indexis once again incremented by 1 using the pre-increment operator. This means that the new value ofindexwill be one greater than its previous value. -
After the if-else block, the method returns the value of
index, incremented by 1 using the pre-increment operator. This means that the returned value will be one greater than its previous value. -
If any of the if conditions in steps 3, 5, or 7 evaluate to false, indicating that the "null" value was not found, an
UnexpectedCharacterExceptionis thrown. This exception provides an error message stating that "Parsing JSON Null" failed because an unexpected character was encountered in theCharArrayCharSource, and includes a reference to the source object.
In summary, the findNullEnd method in the CharArrayCharSource class is responsible for locating the end position of a "null" value in a JSON string. It checks if the characters at a specific position in the string match the sequence 'u', 'l', 'l', and returns the position of the last character of the match. If the expected sequence is not found, an exception is thrown.

public boolean matchChars(final int startIndex, final int endIndex, CharSequence key)
@Override
public boolean matchChars(final int startIndex, final int endIndex, CharSequence key) {
final int length = endIndex - startIndex;
int idx = startIndex;
switch(length) {
case 1:
return key.charAt(0) == data[idx];
case 2:
return key.charAt(0) == data[idx] && key.charAt(1) == data[idx + 1];
case 3:
return key.charAt(0) == data[idx] && key.charAt(1) == data[idx + 1] && key.charAt(2) == data[idx + 2];
case 4:
return key.charAt(0) == data[idx] && key.charAt(1) == data[idx + 1] && key.charAt(2) == data[idx + 2] && key.charAt(3) == data[idx + 3];
case 5:
return key.charAt(1) == data[idx + 1] && key.charAt(3) == data[idx + 3] && key.charAt(0) == data[idx] && key.charAt(2) == data[idx + 2] && key.charAt(4) == data[idx + 4];
case 6:
return key.charAt(0) == data[idx] && key.charAt(5) == data[idx + 5] && key.charAt(3) == data[idx + 3] && key.charAt(1) == data[idx + 1] && key.charAt(2) == data[idx + 2] && key.charAt(4) == data[idx + 4];
case 7:
return key.charAt(0) == data[idx] && key.charAt(6) == data[idx + 6] && key.charAt(3) == data[idx + 3] && key.charAt(1) == data[idx + 1] && key.charAt(5) == data[idx + 5] && key.charAt(2) == data[idx + 2] && key.charAt(4) == data[idx + 4];
case 8:
return key.charAt(0) == data[idx] && key.charAt(7) == data[idx + 7] && key.charAt(3) == data[idx + 3] && key.charAt(1) == data[idx + 1] && key.charAt(5) == data[idx + 5] && key.charAt(2) == data[idx + 2] && key.charAt(6) == data[idx + 6] && key.charAt(4) == data[idx + 4];
case 9:
return key.charAt(0) == data[idx] && key.charAt(8) == data[idx + 8] && key.charAt(2) == data[idx + 2] && key.charAt(6) == data[idx + 6] && key.charAt(3) == data[idx + 3] && key.charAt(7) == data[idx + 7] && key.charAt(4) == data[idx + 4] && key.charAt(5) == data[idx + 5] && key.charAt(1) == data[idx + 1];
case 10:
return key.charAt(0) == data[idx] && key.charAt(9) == data[idx + 9] && key.charAt(6) == data[idx + 6] && key.charAt(3) == data[idx + 3] && key.charAt(7) == data[idx + 7] && key.charAt(2) == data[idx + 2] && key.charAt(4) == data[idx + 4] && key.charAt(5) == data[idx + 5] && key.charAt(1) == data[idx + 1] && key.charAt(8) == data[idx + 8];
case 11:
return key.charAt(0) == data[idx] && key.charAt(10) == data[idx + 10] && key.charAt(6) == data[idx + 6] && key.charAt(3) == data[idx + 3] && key.charAt(7) == data[idx + 7] && key.charAt(2) == data[idx + 2] && key.charAt(9) == data[idx + 9] && key.charAt(4) == data[idx + 4] && key.charAt(5) == data[idx + 5] && key.charAt(1) == data[idx + 1] && key.charAt(8) == data[idx + 8];
case 12:
return key.charAt(0) == data[idx] && key.charAt(11) == data[idx + 11] && key.charAt(3) == data[idx + 3] && key.charAt(7) == data[idx + 7] && key.charAt(2) == data[idx + 2] && key.charAt(6) == data[idx + 6] && key.charAt(9) == data[idx + 9] && key.charAt(4) == data[idx + 4] && key.charAt(5) == data[idx + 5] && key.charAt(10) == data[idx + 10] && key.charAt(1) == data[idx + 1] && key.charAt(8) == data[idx + 8];
default:
final int start = 0;
final int end = length - 1;
final int middle = length / 2;
if (key.charAt(start) == data[idx] && key.charAt(end) == data[idx + end] && key.charAt(middle) == data[idx + middle]) {
for (int i = 1; i < length; i++) {
if (key.charAt(i) != data[idx + i]) {
return false;
}
}
return true;
} else {
return false;
}
}
}The matchChars method is a method defined in the CharArrayCharSource class, which is used for comparing a character sequence with a portion of a character array.
Here's a step-by-step description of what the method does:
-
The method takes three parameters:
startIndex,endIndex, andkey. These parameters indicate the range of the character array to be compared and the character sequence to compare it with. -
The method calculates the length of the character array range by subtracting the
startIndexfrom theendIndex. -
It initializes a variable
idxwith the value of thestartIndex. -
The method then uses a
switchstatement based on the length of the character array range:-
For lengths 1 to 12, it compares each corresponding character in the
keysequence with the corresponding character in the character array range using thecharAtmethod. If all the characters match, it returnstrue, otherwisefalse. -
For lengths greater than 12, it performs a more generic comparison. It checks if the first, middle, and last characters of the
keysequence match the corresponding characters in the character array range. If they do, it iterates through the rest of the characters in thekeysequence and character array range, comparing each character. If all the characters match, it returnstrue, otherwisefalse. -
If none of the above cases match, it returns
false.
-
Overall, the matchChars method is used to determine if a given character sequence matches a specific portion of a character array. It uses a combination of specific comparisons for shorter lengths and a more generic comparison for longer lengths.

public boolean isInteger(int offset, int end) {
int len = end - offset;
final char[] digitChars = data;
final boolean negative = (digitChars[offset] == '-');
final int cmpLen = negative ? MIN_INT_STR_LENGTH : MAX_INT_STR_LENGTH;
if (len < cmpLen)
return true;
if (len > cmpLen)
return false;
final char[] cmpStr = negative ? MIN_INT_CHARS : MAX_INT_CHARS;
for (int i = 0; i < cmpLen; ++i) {
int diff = digitChars[offset + i] - cmpStr[i];
if (diff != 0) {
return (diff < 0);
}
}
return true;
}The isInteger method, defined in the io.nats.jparse.source.CharArrayCharSource class, determines whether a sequence of characters in an array represents an integer. The method takes in two parameters - offset and end, which specify the range of characters in the array to be considered.
Here is a step-by-step description of what the method does based on its body:
- Calculate the length of the sequence by subtracting the
offsetfrom theendparameter and store it in thelenvariable. - Get a reference to the character array (
data) that contains the sequence of characters to be examined. - Determine whether the first character in the sequence is a negative sign ('-') and store the result in the
negativevariable. - Determine whether the length of the sequence (
len) is less than a predefined length for comparisons (MIN_INT_STR_LENGTHorMAX_INT_STR_LENGTH). If it is, returntruesince the sequence is shorter than the minimum length required for a valid integer representation. - If the length of the sequence is longer than the predefined length, return
falsesince the sequence is longer than the maximum length required for a valid integer representation. - Determine which predefined character array to use for comparison (
MIN_INT_CHARSorMAX_INT_CHARS), based on whether the sequence represents a negative or positive integer, and store it in thecmpStrvariable. - Iterate over each character in the sequence, comparing it with the corresponding character in the predefined character array.
- In each iteration, calculate the difference between the current character in the sequence and the corresponding character in the predefined character array and store it in the
diffvariable. - If the difference is non-zero, return
trueif the difference is less than zero, indicating that the sequence is a smaller number than the predefined comparison value. - If all characters in the sequence match the corresponding characters in the predefined character array, return
trueto indicate that the sequence represents a valid integer. - If no non-zero differences are found, return
truesince the sequence matches the predefined comparison value.
In summary, the isInteger method determines whether a sequence of characters in an array represents an integer by comparing it with predefined character arrays and performing character-by-character comparisons. It handles cases where the sequence is too short or too long, and also distinguishes between negative and positive integers.

public String errorDetails(String message, int index, int ch)
@Override
public String errorDetails(String message, int index, int ch) {
StringBuilder buf = new StringBuilder(255);
final char[] array = data;
buf.append(message).append("\n");
buf.append("\n");
buf.append("The current character read is " + debugCharDescription(ch)).append('\n');
int line = 0;
int lastLineIndex = 0;
for (int i = 0; i < index && i < array.length; i++) {
if (array[i] == '\n') {
line++;
lastLineIndex = i + 1;
}
}
int count = 0;
for (int i = lastLineIndex; i < array.length; i++, count++) {
if (array[i] == '\n') {
break;
}
}
buf.append("line number " + (line + 1)).append('\n');
buf.append("index number " + index).append('\n');
try {
buf.append(new String(array, lastLineIndex, count)).append('\n');
} catch (Exception ex) {
try {
int start = index = (index - 10 < 0) ? 0 : index - 10;
buf.append(new String(array, start, index)).append('\n');
} catch (Exception ex2) {
buf.append(new String(array)).append('\n');
}
}
for (int i = 0; i < (index - lastLineIndex); i++) {
buf.append('.');
}
buf.append('^');
return buf.toString();
}This method, defined in the class io.nats.jparse.source.CharArrayCharSource, is used to generate an error message with details about the error encountered at a specific index in the character array.
public String errorDetails(String message, int index, int ch)-
message(String): A custom error message to prepend to the error details. -
index(int): The index at which the error occurred in the character array. -
ch(int): The current character being processed when the error occurred.
-
String: The generated error message with details.
- Create a
StringBuilderinstance namedbuf, initialized with an initial capacity of 255. - Create a local variable named
arrayof typechar[], initialized with the character arraydatafrom the class. - Append the
messageparameter and a newline character tobuf. - Append an additional newline character to
buf. - Append a formatted string to
bufthat describes the current character being processed, using thedebugCharDescriptionmethod. - Initialize two local variables,
lineandlastLineIndex, both set to 0. - Iterate from
i= 0 toindex, exclusive, and as long asiis within the length ofarray.- If the character
array[i]is a newline character, incrementlineby 1 and updatelastLineIndextoi + 1.
- If the character
- Initialize two local variables,
countset to 0, andiset tolastLineIndex. - Iterate from
i=lastLineIndexto the end ofarray.- If the character
array[i]is a newline character, break the loop. - Otherwise, increment
countby 1.
- If the character
- Append a formatted string to
bufthat states the line number, which isline + 1. - Append a formatted string to
bufthat states the index number, which isindex. - Attempt the following block, and catch any exceptions thrown:
- Append a substring of
arraytobuf, starting atlastLineIndexwith a length ofcount.
- Append a substring of
- If an exception was caught in the above block, attempt the following block, and catch any exceptions thrown:
- Calculate the start index by subtracting 10 from
index. If the result is less than 0, setstartto 0. - Append a substring of
arraytobuf, starting atstartwith a length ofindex.
- Calculate the start index by subtracting 10 from
- If an exception was caught in the above block, append the entire
arraytobuf. - Append a sequence of dots (
.) tobuf, equal to the difference betweenindexandlastLineIndex. - Append a
^character tobuf. - Return the string representation of
buf.
- Java Open AI Client
- Using ChatGpt embeddings and hyde to improve search results
- Anthropics Claude Chatbot Gets Upgrade
- Elon Musks XAi new frontier for artificial intelligence
- Using Mockito to test JAI Java Open AI Client
- Fine tuning journey with Open AI API
- Using Open AI to create callback functions, the basis for plugins
- Using Java Open AI Client Async
- Fastest Java JSON Parser
- Java Open AI API Client on Github
- Medium: Introducing Java Open AI Client
- Medium: Using ChatGPT, Embeddings, and HyDE to Improve Search Results