1818import java .io .EOFException ;
1919import java .io .IOException ;
2020import java .nio .ByteBuffer ;
21+ import java .util .zip .DataFormatException ;
2122import java .util .zip .Inflater ;
2223
2324public final class ZlibDataReader extends DataReader {
24- static final InputContext .CacheKey <Inflater > INFLATER_CACHE_KEY = new InputContext .CacheKey <>();
25+ static final InputContext .CacheKey <Inflater > INFLATER_CACHE_KEY = new InputContext .CacheKey <>() {
26+
27+ @ Override
28+ protected Inflater create (InputContext context ) {
29+ return new Inflater ();
30+ }
31+
32+ @ Override
33+ public void close (Inflater value ) {
34+ value .end ();
35+ }
36+ };
2537 private final Inflater inflater ;
2638
2739 ZlibDataReader (InputContext context , long compressedSize ) {
2840 super (context , context .getDecompressBuffer ());
29- this .inflater = INFLATER_CACHE_KEY .getOrCreate (context , Inflater :: new );
41+ this .inflater = INFLATER_CACHE_KEY .get (context );
3042 this .remainingInput = compressedSize ;
3143 }
3244
@@ -36,23 +48,46 @@ public void ensureBufferRemaining(int required) throws IOException {
3648 return ;
3749 }
3850
51+ if (inflater .finished () || inflater .needsDictionary ()) {
52+ throw new EOFException ("Inflater finished or needs dictionary" );
53+ }
54+
3955 buffer .ensureCapacity (required );
40- ByteBuffer byteBuffer = this .buffer .getByteBuffer ();
41-
42- // TODO
43-
44- // do {
45- // if (inflater.finished() || inflater.needsDictionary()) {
46- // throw new EOFException();
47- // }
48- //
49- // if (inflater.needsInput()) {
50- // if (context.rawReader.buffer.remaining() == 0) {
51- // context.rawReader.ensureBufferRemaining(1);
52- // }
53- //
54- // inflater.setInput(context.rawReader.buffer.getByteBuffer());
55- // }
56- // } while ((n = inflater.inflate(b, off, len)) == 0);
56+ ByteBuffer output = this .buffer .getByteBuffer ();
57+ output .compact ();
58+
59+ do {
60+ if (inflater .finished () || inflater .needsDictionary ()) {
61+ throw new EOFException ();
62+ }
63+
64+ if (inflater .needsInput ()) {
65+ if (context .rawReader .buffer .remaining () == 0 ) {
66+ context .rawReader .ensureBufferRemaining (1 );
67+ }
68+ inflater .setInput (context .rawReader .buffer .getByteBuffer ());
69+ }
70+
71+ try {
72+ inflater .inflate (output );
73+ } catch (DataFormatException exception ) {
74+ throw new IOException (exception );
75+ }
76+
77+ } while (output .position () < required );
78+
79+ inflater .setInput (EMPTY_BYTE_ARRAY );
80+ output .flip ();
81+ }
82+
83+ @ Override
84+ public void close () throws IOException {
85+ inflater .end ();
86+ context .releaseDecompressBuffer (buffer );
87+
88+ inflater .reset ();
89+ INFLATER_CACHE_KEY .release (context , inflater );
5790 }
91+
92+ private static final byte [] EMPTY_BYTE_ARRAY = new byte [0 ];
5893}
0 commit comments