@@ -350,10 +350,7 @@ default String findString(final boolean saveString, final int blockSize,
350
350
final StringBuilder out = new StringBuilder ();
351
351
final long startPos = offset ();
352
352
long bytesDropped = 0 ;
353
- final long inputLen = length ();
354
- long maxLen = inputLen - startPos ;
355
- final boolean tooLong = saveString && maxLen > MAX_SEARCH_SIZE ;
356
- if (tooLong ) maxLen = MAX_SEARCH_SIZE ;
353
+ final long maxLen = saveString ? MAX_SEARCH_SIZE : Long .MAX_VALUE ;
357
354
boolean match = false ;
358
355
int maxTermLen = 0 ;
359
356
for (final String term : terminators ) {
@@ -366,7 +363,10 @@ default String findString(final boolean saveString, final int blockSize,
366
363
new DataHandleInputStream <>(this ), getEncoding ());
367
364
final char [] buf = new char [blockSize ];
368
365
long loc = 0 ;
369
- while (loc < maxLen && offset () < length () - 1 ) {
366
+ int r = 0 ;
367
+
368
+ // NB: we need at least 2 bytes to read a char
369
+ while (loc < maxLen && ((r = in .read (buf , 0 , blockSize )) > 1 )) {
370
370
// if we're not saving the string, drop any old, unnecessary output
371
371
if (!saveString ) {
372
372
final int outLen = out .length ();
@@ -378,16 +378,12 @@ default String findString(final boolean saveString, final int blockSize,
378
378
bytesDropped += dropIndex ;
379
379
}
380
380
}
381
-
382
- // read block from stream
383
- final int r = in .read (buf , 0 , blockSize );
384
- if (r <= 0 ) throw new IOException ("Cannot read from stream: " + r );
385
-
386
381
// append block to output
387
382
out .append (buf , 0 , r );
388
383
389
384
// check output, returning smallest possible string
390
- int min = Integer .MAX_VALUE , tagLen = 0 ;
385
+ int min = Integer .MAX_VALUE ;
386
+ int tagLen = 0 ;
391
387
for (final String t : terminators ) {
392
388
final int len = t .length ();
393
389
final int start = (int ) (loc - bytesDropped - len );
@@ -415,7 +411,9 @@ default String findString(final boolean saveString, final int blockSize,
415
411
}
416
412
417
413
// no match
418
- if (tooLong ) throw new IOException ("Maximum search length reached." );
414
+ if (loc > MAX_SEARCH_SIZE ) {
415
+ throw new IOException ("Maximum search length reached." );
416
+ }
419
417
return saveString ? out .toString () : null ;
420
418
}
421
419
0 commit comments