changelog.md
[nikiroo-utils.git] / src / be / nikiroo / utils / streams / NextableInputStreamStep.java
CommitLineData
8e76f6ab 1package be.nikiroo.utils.streams;
4098af70 2
63b46ca9
NR
3import java.io.InputStream;
4
5/**
6 * Divide an {@link InputStream} into sub-streams.
7 *
8 * @author niki
9 */
4098af70
N
10public class NextableInputStreamStep {
11 private int stopAt;
4098af70
N
12 private int resumeLen;
13 private int last = -1;
14 private int skip;
15
63b46ca9
NR
16 /**
17 * Create a new divider that will separate the sub-streams each time it sees
18 * this byte.
19 * <p>
20 * Note that the byte will be bypassed by the {@link InputStream} as far as
21 * the consumers will be aware.
22 *
23 * @param byt
24 * the byte at which to separate two sub-streams
25 */
4098af70
N
26 public NextableInputStreamStep(int byt) {
27 stopAt = byt;
28 }
29
63b46ca9
NR
30 /**
31 * Check if we need to stop the {@link InputStream} reading at some point in
32 * the current buffer.
33 * <p>
34 * If we do, return the index at which to stop; if not, return -1.
35 * <p>
36 * This method will <b>not</b> return the same index a second time (unless
37 * we cleared the buffer).
38 *
39 * @param buffer
40 * the buffer to check
41 * @param pos
42 * the current position of what was read in the buffer
43 * @param len
44 * the maximum index to use in the buffer (anything above that is
45 * not to be used)
46 *
47 * @return the index at which to stop, or -1
48 */
4098af70
N
49 public int stop(byte[] buffer, int pos, int len) {
50 for (int i = pos; i < len; i++) {
51 if (buffer[i] == stopAt) {
52 if (i > this.last) {
53 // we skip the sep
54 this.skip = 1;
63b46ca9 55
4098af70
N
56 this.resumeLen = len;
57 this.last = i;
58 return i;
59 }
60 }
61 }
62
63 return -1;
64 }
65
63b46ca9
NR
66 /**
67 * Get the maximum index to use in the buffer used in
68 * {@link NextableInputStreamStep#stop(byte[], int, int)} at resume time.
69 *
70 * @return the index
71 */
4098af70
N
72 public int getResumeLen() {
73 return resumeLen;
74 }
63b46ca9
NR
75
76 /**
77 * Get the number of bytes to skip at resume time.
78 *
79 * @return the number of bytes to skip
80 */
81 public int getResumeSkip() {
4098af70
N
82 return skip;
83 }
84
63b46ca9
NR
85 /**
86 * Clear the information we may have kept about the current buffer
87 * <p>
88 * You should call this method each time you change the content of the
89 * buffer used in {@link NextableInputStreamStep#stop(byte[], int, int)}.
90 */
4098af70
N
91 public void clearBuffer() {
92 this.last = -1;
4098af70
N
93 this.skip = 0;
94 this.resumeLen = 0;
95 }
4098af70 96}