Skip to content

Commit ffaec27

Browse files
committed
#128: prevent OutOfBoundsException on trailing newline
1 parent 21aa25a commit ffaec27

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

shared/src/main/scala/scala/util/parsing/input/OffsetPosition.scala

+6-4
Original file line numberDiff line numberDiff line change
@@ -63,12 +63,14 @@ case class OffsetPosition(source: CharSequence, offset: Int) extends Position {
6363
* @return the line at `offset` (not including a newline)
6464
*/
6565
def lineContents: String = {
66-
val endIndex = if (source.charAt(index(line) - 1) == '\n') {
67-
index(line) - 1
66+
val lineStart = index(line - 1)
67+
val lineEnd = index(line)
68+
val endIndex = if ( lineStart < lineEnd && source.charAt(lineEnd - 1) == '\n') {
69+
lineEnd - 1
6870
} else {
69-
index(line)
71+
lineEnd
7072
}
71-
source.subSequence(index(line - 1), endIndex).toString
73+
source.subSequence(lineStart, endIndex).toString
7274
}
7375

7476
/** Returns a string representation of the `Position`, of the form `line.column`. */
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package scala.util.parsing.input
2+
3+
import org.junit.Test
4+
import org.junit.Assert.assertEquals
5+
6+
class OffsetPositionTest {
7+
@Test
8+
def printLineContentsWithTrailingNewLine: Unit = {
9+
val op = new OffsetPosition("\n", 1)
10+
assertEquals(op.lineContents, "")
11+
}
12+
13+
@Test
14+
def printLineContentsWithEmptySource: Unit = {
15+
val op = new OffsetPosition("", 0)
16+
assertEquals(op.lineContents, "")
17+
}
18+
}

0 commit comments

Comments
 (0)