1/*
2 * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package java.util.zip;
27
28import java.io.FilterInputStream;
29import java.io.InputStream;
30import java.io.IOException;
31import java.io.EOFException;
32
33/**
34 * This class implements a stream filter for uncompressing data in the
35 * "deflate" compression format. It is also used as the basis for other
36 * decompression filters, such as GZIPInputStream.
37 *
38 * @see         Inflater
39 * @author      David Connelly
40 * @since 1.1
41 */
42public
43class InflaterInputStream extends FilterInputStream {
44    /**
45     * Decompressor for this stream.
46     */
47    protected Inflater inf;
48
49    /**
50     * Input buffer for decompression.
51     */
52    protected byte[] buf;
53
54    /**
55     * Length of input buffer.
56     */
57    protected int len;
58
59    private boolean closed = false;
60    // this flag is set to true after EOF has reached
61    private boolean reachEOF = false;
62
63    /**
64     * Check to make sure that this stream has not been closed
65     */
66    private void ensureOpen() throws IOException {
67        if (closed) {
68            throw new IOException("Stream closed");
69        }
70    }
71
72
73    /**
74     * Creates a new input stream with the specified decompressor and
75     * buffer size.
76     * @param in the input stream
77     * @param inf the decompressor ("inflater")
78     * @param size the input buffer size
79     * @exception IllegalArgumentException if {@code size <= 0}
80     */
81    public InflaterInputStream(InputStream in, Inflater inf, int size) {
82        super(in);
83        if (in == null || inf == null) {
84            throw new NullPointerException();
85        } else if (size <= 0) {
86            throw new IllegalArgumentException("buffer size <= 0");
87        }
88        this.inf = inf;
89        buf = new byte[size];
90    }
91
92    /**
93     * Creates a new input stream with the specified decompressor and a
94     * default buffer size.
95     * @param in the input stream
96     * @param inf the decompressor ("inflater")
97     */
98    public InflaterInputStream(InputStream in, Inflater inf) {
99        this(in, inf, 512);
100    }
101
102    boolean usesDefaultInflater = false;
103
104    /**
105     * Creates a new input stream with a default decompressor and buffer size.
106     * @param in the input stream
107     */
108    public InflaterInputStream(InputStream in) {
109        this(in, new Inflater());
110        usesDefaultInflater = true;
111    }
112
113    private byte[] singleByteBuf = new byte[1];
114
115    /**
116     * Reads a byte of uncompressed data. This method will block until
117     * enough input is available for decompression.
118     * @return the byte read, or -1 if end of compressed input is reached
119     * @exception IOException if an I/O error has occurred
120     */
121    public int read() throws IOException {
122        ensureOpen();
123        return read(singleByteBuf, 0, 1) == -1 ? -1 : Byte.toUnsignedInt(singleByteBuf[0]);
124    }
125
126    /**
127     * Reads uncompressed data into an array of bytes. If <code>len</code> is not
128     * zero, the method will block until some input can be decompressed; otherwise,
129     * no bytes are read and <code>0</code> is returned.
130     * @param b the buffer into which the data is read
131     * @param off the start offset in the destination array <code>b</code>
132     * @param len the maximum number of bytes read
133     * @return the actual number of bytes read, or -1 if the end of the
134     *         compressed input is reached or a preset dictionary is needed
135     * @exception  NullPointerException If <code>b</code> is <code>null</code>.
136     * @exception  IndexOutOfBoundsException If <code>off</code> is negative,
137     * <code>len</code> is negative, or <code>len</code> is greater than
138     * <code>b.length - off</code>
139     * @exception ZipException if a ZIP format error has occurred
140     * @exception IOException if an I/O error has occurred
141     */
142    public int read(byte[] b, int off, int len) throws IOException {
143        ensureOpen();
144        if (b == null) {
145            throw new NullPointerException();
146        } else if (off < 0 || len < 0 || len > b.length - off) {
147            throw new IndexOutOfBoundsException();
148        } else if (len == 0) {
149            return 0;
150        }
151        try {
152            int n;
153            while ((n = inf.inflate(b, off, len)) == 0) {
154                if (inf.finished() || inf.needsDictionary()) {
155                    reachEOF = true;
156                    return -1;
157                }
158                if (inf.needsInput()) {
159                    fill();
160                }
161            }
162            return n;
163        } catch (DataFormatException e) {
164            String s = e.getMessage();
165            throw new ZipException(s != null ? s : "Invalid ZLIB data format");
166        }
167    }
168
169    /**
170     * Returns 0 after EOF has been reached, otherwise always return 1.
171     * <p>
172     * Programs should not count on this method to return the actual number
173     * of bytes that could be read without blocking.
174     *
175     * @return     1 before EOF and 0 after EOF.
176     * @exception  IOException  if an I/O error occurs.
177     *
178     */
179    public int available() throws IOException {
180        ensureOpen();
181        if (reachEOF) {
182            return 0;
183        } else if (inf.finished()) {
184            // the end of the compressed data stream has been reached
185            reachEOF = true;
186            return 0;
187        } else {
188            return 1;
189        }
190    }
191
192    private byte[] b = new byte[512];
193
194    /**
195     * Skips specified number of bytes of uncompressed data.
196     * @param n the number of bytes to skip
197     * @return the actual number of bytes skipped.
198     * @exception IOException if an I/O error has occurred
199     * @exception IllegalArgumentException if {@code n < 0}
200     */
201    public long skip(long n) throws IOException {
202        if (n < 0) {
203            throw new IllegalArgumentException("negative skip length");
204        }
205        ensureOpen();
206        int max = (int)Math.min(n, Integer.MAX_VALUE);
207        int total = 0;
208        while (total < max) {
209            int len = max - total;
210            if (len > b.length) {
211                len = b.length;
212            }
213            len = read(b, 0, len);
214            if (len == -1) {
215                reachEOF = true;
216                break;
217            }
218            total += len;
219        }
220        return total;
221    }
222
223    /**
224     * Closes this input stream and releases any system resources associated
225     * with the stream.
226     * @exception IOException if an I/O error has occurred
227     */
228    public void close() throws IOException {
229        if (!closed) {
230            if (usesDefaultInflater)
231                inf.end();
232            in.close();
233            closed = true;
234        }
235    }
236
237    /**
238     * Fills input buffer with more data to decompress.
239     * @exception IOException if an I/O error has occurred
240     */
241    protected void fill() throws IOException {
242        ensureOpen();
243        len = in.read(buf, 0, buf.length);
244        if (len == -1) {
245            throw new EOFException("Unexpected end of ZLIB input stream");
246        }
247        inf.setInput(buf, 0, len);
248    }
249
250    /**
251     * Tests if this input stream supports the <code>mark</code> and
252     * <code>reset</code> methods. The <code>markSupported</code>
253     * method of <code>InflaterInputStream</code> returns
254     * <code>false</code>.
255     *
256     * @return  a <code>boolean</code> indicating if this stream type supports
257     *          the <code>mark</code> and <code>reset</code> methods.
258     * @see     java.io.InputStream#mark(int)
259     * @see     java.io.InputStream#reset()
260     */
261    public boolean markSupported() {
262        return false;
263    }
264
265    /**
266     * Marks the current position in this input stream.
267     *
268     * <p> The <code>mark</code> method of <code>InflaterInputStream</code>
269     * does nothing.
270     *
271     * @param   readlimit   the maximum limit of bytes that can be read before
272     *                      the mark position becomes invalid.
273     * @see     java.io.InputStream#reset()
274     */
275    public synchronized void mark(int readlimit) {
276    }
277
278    /**
279     * Repositions this stream to the position at the time the
280     * <code>mark</code> method was last called on this input stream.
281     *
282     * <p> The method <code>reset</code> for class
283     * <code>InflaterInputStream</code> does nothing except throw an
284     * <code>IOException</code>.
285     *
286     * @exception  IOException  if this method is invoked.
287     * @see     java.io.InputStream#mark(int)
288     * @see     java.io.IOException
289     */
290    public synchronized void reset() throws IOException {
291        throw new IOException("mark/reset not supported");
292    }
293}
294