|
8 | 8 | import org.openjdk.jmh.annotations.*; |
9 | 9 | import org.openjdk.jmh.infra.Blackhole; |
10 | 10 |
|
11 | | -import java.io.ByteArrayInputStream; |
12 | 11 | import java.io.IOException; |
13 | 12 | import java.io.InputStream; |
14 | 13 | import java.nio.ByteBuffer; |
15 | 14 | import java.util.List; |
16 | 15 | import java.util.concurrent.TimeUnit; |
| 16 | +import java.util.zip.DataFormatException; |
17 | 17 | import java.util.zip.Inflater; |
18 | | -import java.util.zip.InflaterInputStream; |
| 18 | +import java.util.zip.ZipException; |
19 | 19 |
|
20 | 20 | @BenchmarkMode(Mode.AverageTime) |
21 | 21 | @OutputTimeUnit(TimeUnit.MICROSECONDS) |
@@ -199,7 +199,52 @@ else if (flushBuffer != null) |
199 | 199 | System.arraycopy(arr, 0, data, 0, data.length); |
200 | 200 | flushBuffer = null; |
201 | 201 | } |
202 | | - return new InflaterInputStream(new ByteArrayInputStream(data), inflater); |
| 202 | + return new FixedInflaterInputStream(inflater, data); |
| 203 | + } |
| 204 | + } |
| 205 | + |
| 206 | + private static class FixedInflaterInputStream extends InputStream { |
| 207 | + private final Inflater inflater; |
| 208 | + |
| 209 | + private boolean closed = false; |
| 210 | + private boolean invalidated = false; |
| 211 | + |
| 212 | + public FixedInflaterInputStream(Inflater inflater, byte[] data) { |
| 213 | + this.inflater = inflater; |
| 214 | + inflater.setInput(data); |
| 215 | + } |
| 216 | + |
| 217 | + @Override |
| 218 | + public void close() { |
| 219 | + closed = true; |
| 220 | + } |
| 221 | + |
| 222 | + @Override |
| 223 | + public int read() throws IOException { |
| 224 | + byte[] buf = new byte[1]; |
| 225 | + return read(buf, 0, 1); |
| 226 | + } |
| 227 | + |
| 228 | + @Override |
| 229 | + public int read(byte[] b, int off, int len) throws IOException { |
| 230 | + if (closed) |
| 231 | + throw new IOException("Stream is closed"); |
| 232 | + if (invalidated) |
| 233 | + throw new IllegalStateException("Decompressor is in an errored state and needs to be reset"); |
| 234 | + if ((b.length | off | len) < 0 || len > b.length - off) |
| 235 | + throw new IndexOutOfBoundsException(); |
| 236 | + if (len == 0) |
| 237 | + return 0; |
| 238 | + if (inflater.needsInput()) |
| 239 | + return -1; |
| 240 | + |
| 241 | + try { |
| 242 | + return inflater.inflate(b, off, len); |
| 243 | + } catch (DataFormatException e) { |
| 244 | + invalidated = true; |
| 245 | + String s = e.getMessage(); |
| 246 | + throw new ZipException(s != null ? s : "Invalid ZLIB data format"); |
| 247 | + } |
203 | 248 | } |
204 | 249 | } |
205 | 250 | } |
0 commit comments