blob: 81c97857c06eee856727758d41b3313c0b5e32e6 [file] [log] [blame]
Stuart McCullochbb014372012-06-07 21:57:32 +00001package aQute.libg.gzip;
2
Stuart McCulloch2286f232012-06-15 13:27:53 +00003import java.io.*;
4import java.util.zip.*;
Stuart McCullochbb014372012-06-07 21:57:32 +00005
6public class GZipUtils {
Stuart McCulloch2286f232012-06-15 13:27:53 +00007
Stuart McCullochbb014372012-06-07 21:57:32 +00008 /**
9 * Determines whether the specified stream contains gzipped data, by
10 * checking for the GZIP magic number, and returns a stream capable of
11 * reading those data.
12 *
13 * @throws IOException
14 */
15 public static InputStream detectCompression(InputStream stream) throws IOException {
16 InputStream buffered;
17 if (stream.markSupported())
18 buffered = stream;
19 else
20 buffered = new BufferedInputStream(stream);
Stuart McCulloch2286f232012-06-15 13:27:53 +000021
Stuart McCullochbb014372012-06-07 21:57:32 +000022 buffered.mark(2);
23 int magic = readUShort(buffered);
24 buffered.reset();
Stuart McCulloch2286f232012-06-15 13:27:53 +000025
Stuart McCullochbb014372012-06-07 21:57:32 +000026 InputStream result;
27 if (magic == GZIPInputStream.GZIP_MAGIC)
28 result = new GZIPInputStream(buffered);
29 else
30 result = buffered;
31 return result;
32 }
33
Stuart McCulloch2286f232012-06-15 13:27:53 +000034 /*
35 * Reads unsigned short in Intel byte order.
36 */
Stuart McCullochbb014372012-06-07 21:57:32 +000037 private static int readUShort(InputStream in) throws IOException {
38 int b = readUByte(in);
39 return (readUByte(in) << 8) | b;
40 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000041
42 /*
43 * Reads unsigned byte.
44 */
45 private static int readUByte(InputStream in) throws IOException {
46 int b = in.read();
47 if (b == -1) {
48 throw new EOFException();
49 }
50 if (b < -1 || b > 255) {
51 // Report on this.in, not argument in; see read{Header, Trailer}.
52 throw new IOException(in.getClass().getName() + ".read() returned value out of range -1..255: " + b);
53 }
54 return b;
Stuart McCullochbb014372012-06-07 21:57:32 +000055 }
Stuart McCullochbb014372012-06-07 21:57:32 +000056
57}