Skip to content

Commit 34aa201

Browse files
committed
benchmarks: implement our own InputStream to read inflaters with fixed data
`InflaterInputStream` is not suited for fixed data and caused exceptions with larger inputs
1 parent 4a4998d commit 34aa201

File tree

1 file changed

+48
-3
lines changed

1 file changed

+48
-3
lines changed

benchmarks/src/jmh/java/dev/freya02/discord/zstd/ZstdStreamingBenchmark.java

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,14 @@
88
import org.openjdk.jmh.annotations.*;
99
import org.openjdk.jmh.infra.Blackhole;
1010

11-
import java.io.ByteArrayInputStream;
1211
import java.io.IOException;
1312
import java.io.InputStream;
1413
import java.nio.ByteBuffer;
1514
import java.util.List;
1615
import java.util.concurrent.TimeUnit;
16+
import java.util.zip.DataFormatException;
1717
import java.util.zip.Inflater;
18-
import java.util.zip.InflaterInputStream;
18+
import java.util.zip.ZipException;
1919

2020
@BenchmarkMode(Mode.AverageTime)
2121
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@@ -199,7 +199,52 @@ else if (flushBuffer != null)
199199
System.arraycopy(arr, 0, data, 0, data.length);
200200
flushBuffer = null;
201201
}
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+
}
203248
}
204249
}
205250
}

0 commit comments

Comments
 (0)