Skip to content

Commit

Permalink
Fix exception `java.lang.StringIndexOutOfBoundsException: String inde…
Browse files Browse the repository at this point in the history
…x out of range: -1` (#12)
  • Loading branch information
d10xa authored Nov 5, 2024
1 parent cce5e26 commit ab67a5a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,18 @@ class JsonDetector {
@tailrec
def loop(i: Int, start: Int, end: Int): (Int, Int) =
val ri = s.length - i - 1
val rchar = s.charAt(ri)
val lchar = s.charAt(i)
val nextEnd = if(end == -1 && rchar == '}') ri else end
val nextStart = if(start == -1 && lchar == '{') i else start
if (s.length/2<i || (nextStart != -1 && nextEnd != -1)) {
(nextStart, nextEnd)
if (ri < 0) {
(-1, -1)
} else {
loop(i + 1, nextStart, nextEnd)
val rchar = s.charAt(ri)
val lchar = s.charAt(i)
val nextEnd = if (end == -1 && rchar == '}') ri else end
val nextStart = if (start == -1 && lchar == '{') i else start
if (s.length / 2 < i || (nextStart != -1 && nextEnd != -1)) {
(nextStart, nextEnd)
} else {
loop(i + 1, nextStart, nextEnd)
}
}
val res = loop(0, -1, -1)
res match
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,14 @@ class JsonPrefixPostfixTest extends munit.FunSuite {
assertEquals(postfixOpt, None)
}

test(
"detectJson should throw StringIndexOutOfBoundsException when jsonDetector returns invalid indices"
) {
val jsonDetector = new JsonDetector()
val jsonPrefixPostfix = new JsonPrefixPostfix(jsonDetector)
val input = "{"
val result = jsonPrefixPostfix.detectJson(input)
assertEquals(result, (input, None, None))
}

}

0 comments on commit ab67a5a

Please sign in to comment.