diff --git a/src/main/java/org/cobbzilla/util/io/ByteLimitedInputStream.java b/src/main/java/org/cobbzilla/util/io/ByteLimitedInputStream.java index af80762..5cf503e 100644 --- a/src/main/java/org/cobbzilla/util/io/ByteLimitedInputStream.java +++ b/src/main/java/org/cobbzilla/util/io/ByteLimitedInputStream.java @@ -18,6 +18,7 @@ public class ByteLimitedInputStream extends InputStream { @Getter private long count = 0; @Getter private long limit; + @Getter private boolean eos = false; public double getPercentDone () { return ((double) count) / ((double) limit); } @@ -27,24 +28,40 @@ public class ByteLimitedInputStream extends InputStream { } @Override public int read(byte[] b) throws IOException { - if (count >= limit) return -1; + if (eosOrLimitExceeded() == -1) return -1; final int read = delegate.read(b); - if (read != -1) count += read; + incr(read); return read; } @Override public int read(byte[] b, int off, int len) throws IOException { - if (count >= limit) return -1; + if (eosOrLimitExceeded() == -1) return -1; final int read = delegate.read(b, off, len); - if (read != -1) count += read; + incr(read); return read; } @Override public int read() throws IOException { - if (count >= limit) return -1; + if (eosOrLimitExceeded() == -1) return -1; final int read = delegate.read(); - if (read != -1) count++; + incr(read); return read; } + public int eosOrLimitExceeded() throws IOException{ + if (count >= limit) { + if (!eos) throw new IOException("cannot continue reading: stream is larger than " + limit + " bytes"); + return -1; + } + return 0; + } + + public void incr(int read) { + if (read == -1) { + eos = true; + } else { + count += read; + } + } + }