Skip to content

Commit e806e6b

Browse files
sarankumarbaskarSarankumar Baskargarydgregory
authored
[IO-891] Fix BoundedReader.skip(long) accounting and bounds handling (#860)
* [IO-891] Fix BoundedReader skip accounting Limit skip requests to the remaining bound and update charsRead with the actual skipped count. * [IO-891] Refine BoundedReader skip bounds fix Keep skip(long) focused on maxCharsFromTargetReader and actual skipped count, without treating mark read-ahead as a hard limit. * Fix Checkstyle build failure --------- Co-authored-by: Sarankumar Baskar <sbaskar@redhat.com> Co-authored-by: Gary Gregory <garydgregory@users.noreply.github.com>
1 parent cfe19ad commit e806e6b

2 files changed

Lines changed: 40 additions & 2 deletions

File tree

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,15 @@ 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+
final int remaining = maxCharsFromTargetReader - charsRead;
139+
if (remaining <= 0) {
140+
return 0;
141+
}
142+
final long skipped = super.skip(Math.min(n, remaining));
143+
charsRead += (int) skipped;
144+
return skipped;
137145
}
138146
}

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

Lines changed: 30 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,33 @@ 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+
}
245275
}

0 commit comments

Comments
 (0)