| 1 | package be.nikiroo.utils.streams; |
| 2 | |
| 3 | import java.io.InputStream; |
| 4 | |
| 5 | /** |
| 6 | * Divide an {@link InputStream} into sub-streams. |
| 7 | * |
| 8 | * @author niki |
| 9 | */ |
| 10 | public class NextableInputStreamStep { |
| 11 | private int stopAt; |
| 12 | private int resumeLen; |
| 13 | private int last = -1; |
| 14 | private int skip; |
| 15 | |
| 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 | */ |
| 26 | public NextableInputStreamStep(int byt) { |
| 27 | stopAt = byt; |
| 28 | } |
| 29 | |
| 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 | */ |
| 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; |
| 55 | |
| 56 | this.resumeLen = len; |
| 57 | this.last = i; |
| 58 | return i; |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | return -1; |
| 64 | } |
| 65 | |
| 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 | */ |
| 72 | public int getResumeLen() { |
| 73 | return resumeLen; |
| 74 | } |
| 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() { |
| 82 | return skip; |
| 83 | } |
| 84 | |
| 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 | */ |
| 91 | public void clearBuffer() { |
| 92 | this.last = -1; |
| 93 | this.skip = 0; |
| 94 | this.resumeLen = 0; |
| 95 | } |
| 96 | } |