X-Git-Url: http://git.nikiroo.be/?p=nikiroo-utils.git;a=blobdiff_plain;f=src%2Fbe%2Fnikiroo%2Futils%2FNextableInputStream.java;h=6f3afc2b261fe439f65c79dbce20602be3bfdd53;hp=0bcbe14ec89a96a26cf56933ef94aef3214cd1a4;hb=4098af704dfa22ce4a60003940753c28030374fa;hpb=2e7584daaf5d2f06d326c21297a71d02dd275a35 diff --git a/src/be/nikiroo/utils/NextableInputStream.java b/src/be/nikiroo/utils/NextableInputStream.java index 0bcbe14..6f3afc2 100644 --- a/src/be/nikiroo/utils/NextableInputStream.java +++ b/src/be/nikiroo/utils/NextableInputStream.java @@ -2,8 +2,13 @@ package be.nikiroo.utils; import java.io.IOException; import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; public class NextableInputStream extends InputStream { + private List steps = new ArrayList(); + private NextableInputStreamStep step = null; + private InputStream in; private boolean eof; private int pos = 0; @@ -14,6 +19,25 @@ public class NextableInputStream extends InputStream { this.in = in; } + public void addStep(NextableInputStreamStep step) { + steps.add(step); + } + + public boolean next() { + if (!hasMoreData() && step != null) { + len = step.getResumeLen(); + pos += step.getSkip(); + eof = false; + step = null; + + checkNexts(false); + + return true; + } + + return false; + } + @Override public int read() throws IOException { preRead(); @@ -40,27 +64,56 @@ public class NextableInputStream extends InputStream { } int done = 0; - while (!eof && done < blen) { + while (hasMoreData() && done < blen) { preRead(); - for (int i = pos; i < blen && i < len; i++) { - b[boff + done] = buffer[i]; - pos++; - done++; + if (hasMoreData()) { + for (int i = pos; i < blen && i < len; i++) { + b[boff + done] = buffer[i]; + pos++; + done++; + } } } return done > 0 ? done : -1; } + @Override + public int available() throws IOException { + return Math.max(0, len - pos); + } + private void preRead() throws IOException { - if (in != null && !eof && pos >= len) { + if (!eof && in != null && pos >= len && step == null) { pos = 0; len = in.read(buffer); - // checkNexts(); + checkNexts(true); } if (pos >= len) { eof = true; } } + + private boolean hasMoreData() { + return !(eof && pos >= len); + } + + private void checkNexts(boolean newBuffer) { + if (!eof) { + for (NextableInputStreamStep step : steps) { + if (newBuffer) { + step.clearBuffer(); + } + + int stopAt = step.stop(buffer, pos, len); + if (stopAt >= 0) { + this.step = step; + len = stopAt; + eof = true; + break; + } + } + } + } }