LineOffsets { public int getOffset(int line, int column) { if (line < 1) { throw new IllegalArgumentException(); } if (column < 0) { throw new IllegalArgumentException(); } if (lineOffsets.containsKey(line)) { return Math.min(lineOffsets.get(line) + column, endOffset); } else { return endOffset; } } LineOffsets(String code); int getStartOffset(Token token); int getEndOffset(Token token); int getOffset(int line, int column);  }
@Test public void getOffset() { LineOffsets lineOffsets = new LineOffsets("int a = 0;\nint b = 0;"); assertThat(lineOffsets.getOffset(2, 4)).isEqualTo(15); assertThat(lineOffsets.getOffset(2, 100)).isEqualTo(21); assertThat(lineOffsets.getOffset(100, 100)).isEqualTo(21); }
@Test public void getOffsetCariageReturnAsNewLine() { LineOffsets lineOffsets = new LineOffsets("\rfoo"); assertThat(lineOffsets.getOffset(1, 0)).isEqualTo(0); assertThat(lineOffsets.getOffset(2, 0)).isEqualTo(1); }
@Test public void getOffsetCariageReturnAndLineFeedAsSingleOffset() { LineOffsets lineOffsets = new LineOffsets("\r\nfoo"); assertThat(lineOffsets.getOffset(1, 0)).isEqualTo(0); assertThat(lineOffsets.getOffset(2, 0)).isEqualTo(1); }
@Test public void getOffsetBadLine() { thrown.expect(IllegalArgumentException.class); LineOffsets lineOffsets = new LineOffsets(""); lineOffsets.getOffset(0, 0); }
@Test public void getOffsetBadColumn() { thrown.expect(IllegalArgumentException.class); LineOffsets lineOffsets = new LineOffsets(""); lineOffsets.getOffset(1, -1); }