|
15 | 15 | */ |
16 | 16 | package org.glavo.nbt.internal.input; |
17 | 17 |
|
| 18 | +import org.jetbrains.annotations.Nullable; |
| 19 | + |
| 20 | +import java.io.EOFException; |
18 | 21 | import java.io.IOException; |
| 22 | +import java.io.InputStream; |
| 23 | +import java.util.Objects; |
19 | 24 |
|
20 | 25 | public abstract non-sealed class BoundedDataReader extends DataReader { |
21 | 26 | private final RawDataReader rawReader; |
@@ -51,4 +56,49 @@ public void close() throws IOException { |
51 | 56 |
|
52 | 57 | getRawReader().skip(endPosition - currentPosition); |
53 | 58 | } |
| 59 | + |
| 60 | + protected final InputStream asInputStream() { |
| 61 | + return new InputStream() { |
| 62 | + private byte @Nullable [] singleByte; |
| 63 | + |
| 64 | + @Override |
| 65 | + public int read() throws IOException { |
| 66 | + if (singleByte == null) { |
| 67 | + singleByte = new byte[1]; |
| 68 | + } |
| 69 | + |
| 70 | + if (read(singleByte) < 1) { |
| 71 | + return -1; |
| 72 | + } else { |
| 73 | + return Byte.toUnsignedInt(singleByte[0]); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + @Override |
| 78 | + public int read(byte[] b, int off, int len) throws IOException { |
| 79 | + Objects.checkFromIndexSize(off, len, b.length); |
| 80 | + if (len == 0) { |
| 81 | + return 0; |
| 82 | + } |
| 83 | + |
| 84 | + long rawRemaining = endPosition - rawReader.position(); |
| 85 | + if (rawRemaining <= 0) { |
| 86 | + return -1; |
| 87 | + } |
| 88 | + |
| 89 | + if (rawReader.getBuffer().remaining() == 0) { |
| 90 | + try { |
| 91 | + rawReader.ensureBufferRemaining(1); |
| 92 | + } catch (EOFException e) { |
| 93 | + return -1; |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + int n = (int) Math.min(Math.min(len, rawReader.getBuffer().remaining()), rawRemaining); |
| 98 | + rawReader.getBuffer().getBytes(b, off, n); |
| 99 | + return n; |
| 100 | + } |
| 101 | + |
| 102 | + }; |
| 103 | + } |
54 | 104 | } |
0 commit comments