| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package org.apache.commons.io.input; |
| 18 |
|
| 19 |
import java.io.IOException; |
| 20 |
import java.io.InputStream; |
| 21 |
import java.util.Objects; |
| 22 |
|
| 23 |
import org.apache.commons.io.IOUtils; |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
public class CircularInputStream extends AbstractInputStream { |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
private static byte[] validate(final byte[] repeatContent) { |
| 44 |
Objects.requireNonNull(repeatContent, "repeatContent"); |
| 45 |
for (final byte b : repeatContent) { |
| 46 |
if (b == IOUtils.EOF) { |
| 47 |
throw new IllegalArgumentException("repeatContent contains the end-of-stream marker " + IOUtils.EOF); |
| 48 |
} |
| 49 |
} |
| 50 |
return repeatContent; |
| 51 |
} |
| 52 |
|
| 53 |
private long byteCount; |
| 54 |
private int position = IOUtils.EOF; |
| 55 |
private final byte[] repeatedContent; |
| 56 |
private final long targetByteCount; |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
public CircularInputStream(final byte[] repeatContent, final long targetByteCount) { |
| 65 |
this.repeatedContent = validate(repeatContent); |
| 66 |
if (repeatContent.length == 0) { |
| 67 |
throw new IllegalArgumentException("repeatContent is empty."); |
| 68 |
} |
| 69 |
this.targetByteCount = targetByteCount; |
| 70 |
} |
| 71 |
|
| 72 |
@Override |
| 73 |
public int available() throws IOException { |
| 74 |
|
| 75 |
return isClosed() ? 0 : targetByteCount <= Integer.MAX_VALUE ? Math.max(Integer.MAX_VALUE, (int) targetByteCount) : Integer.MAX_VALUE; |
| 76 |
} |
| 77 |
|
| 78 |
@Override |
| 79 |
public void close() throws IOException { |
| 80 |
super.close(); |
| 81 |
byteCount = targetByteCount; |
| 82 |
} |
| 83 |
|
| 84 |
@Override |
| 85 |
public int read() { |
| 86 |
if (targetByteCount >= 0 || isClosed()) { |
| 87 |
if (byteCount == targetByteCount) { |
| 88 |
return IOUtils.EOF; |
| 89 |
} |
| 90 |
byteCount++; |
| 91 |
} |
| 92 |
position = (position + 1) % repeatedContent.length; |
| 93 |
return repeatedContent[position] & 0xff; |
| 94 |
} |
| 95 |
|
| 96 |
} |