Skip to content

Commit 86cd859

Browse files
author
Sarankumar Baskar
committed
[IO-891] Fix BoundedReader skip accounting
Limit skip requests to the remaining bound and update charsRead with the actual skipped count.
1 parent 0c547ad commit 86cd859

2 files changed

Lines changed: 52 additions & 2 deletions

File tree

src/main/java/org/apache/commons/io/input/BoundedReader.java

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,18 @@ public void reset() throws IOException {
132132

133133
@Override
134134
public long skip(final long n) throws IOException {
135-
charsRead += n;
136-
return super.skip(n);
135+
if (n <= 0) {
136+
return super.skip(n);
137+
}
138+
int remaining = maxCharsFromTargetReader - charsRead;
139+
if (markedAt >= 0) {
140+
remaining = Math.min(remaining, readAheadLimit - (charsRead - markedAt));
141+
}
142+
if (remaining <= 0) {
143+
return 0;
144+
}
145+
final long skipped = super.skip(Math.min(n, remaining));
146+
charsRead += (int) skipped;
147+
return skipped;
137148
}
138149
}

src/test/java/org/apache/commons/io/input/BoundedReaderTest.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424

2525
import java.io.BufferedReader;
2626
import java.io.File;
27+
import java.io.FilterReader;
2728
import java.io.IOException;
2829
import java.io.LineNumberReader;
2930
import java.io.Reader;
@@ -242,4 +243,42 @@ void testSkipTest() throws IOException {
242243
assertEquals(-1, mr.read());
243244
}
244245
}
246+
247+
@Test
248+
void testSkipDoesNotExceedBound() throws IOException {
249+
try (BoundedReader mr = new BoundedReader(new StringReader("01234567890"), 3)) {
250+
assertEquals(3, mr.skip(100));
251+
assertEquals(-1, mr.read());
252+
}
253+
}
254+
255+
@Test
256+
void testSkipDoesNotOverflowCharsRead() throws IOException {
257+
try (BoundedReader mr = new BoundedReader(new StringReader("01234567890"), 3)) {
258+
assertEquals(3, mr.skip(Long.MAX_VALUE));
259+
assertEquals(-1, mr.read());
260+
}
261+
}
262+
263+
@Test
264+
void testSkipUsesActualSkippedCount() throws IOException {
265+
try (BoundedReader mr = new BoundedReader(new FilterReader(new StringReader("01234567890")) {
266+
@Override
267+
public long skip(final long n) throws IOException {
268+
return super.skip(Math.min(n, 2));
269+
}
270+
}, 5)) {
271+
assertEquals(2, mr.skip(5));
272+
assertEquals('2', mr.read());
273+
}
274+
}
275+
276+
@Test
277+
void testSkipRespectsReadAheadLimit() throws IOException {
278+
try (BoundedReader mr = new BoundedReader(new StringReader("01234567890"), 10)) {
279+
mr.mark(3);
280+
assertEquals(3, mr.skip(100));
281+
assertEquals(-1, mr.read());
282+
}
283+
}
245284
}

0 commit comments

Comments
 (0)