1 5 package org.h2.compress; 6 7 import java.io.IOException ; 8 import java.io.InputStream ; 9 10 public class LZFInputStream extends InputStream { 11 12 private InputStream in; 13 private CompressLZF decompress = new CompressLZF(); 14 private int pos; 15 private int bufferLength; 16 private byte[] inBuffer; 17 private byte[] buffer; 18 19 public LZFInputStream(InputStream in) throws IOException { 20 this.in = in; 21 if(readInt() != LZFOutputStream.MAGIC) { 22 throw new IOException ("Not an LZFInputStream"); 23 } 24 } 25 26 private byte[] ensureSize(byte[] buff, int len) { 27 return buff == null || buff.length < len ? new byte[len] : buff; 28 } 29 30 private void fillBuffer() throws IOException { 31 if(buffer != null && pos < bufferLength) { 32 return; 33 } 34 int len = readInt(); 35 if(decompress == null) { 36 this.bufferLength = 0; 38 } else if(len < 0) { 39 len = -len; 40 buffer = ensureSize(buffer, len); 41 readFully(buffer, len); 42 this.bufferLength = len; 43 } else { 44 inBuffer = ensureSize(inBuffer, len); 45 int size = readInt(); 46 readFully(inBuffer, len); 47 buffer = ensureSize(buffer, size); 48 try { 49 decompress.expand(inBuffer, 0, len, buffer, 0, size); 50 } catch(Exception e) { 51 throw new IOException ("Error decompressing bytes"); 52 } 53 this.bufferLength = size; 54 } 55 pos = 0; 56 } 57 58 private void readFully(byte[] buff, int len) throws IOException { 59 int off = 0; 60 while(len > 0) { 61 int l = in.read(buff, off, len); 62 len -= l; 63 off += l; 64 } 65 } 66 67 private int readInt() throws IOException { 68 int x = in.read(); 69 if(x<0) { 70 close(); 71 decompress = null; 72 return 0; 73 } 74 x = (x<< 24) + (in.read() << 16) + (in.read() << 8) + in.read(); 75 return x; 76 } 77 78 public int read() throws IOException { 79 fillBuffer(); 80 if(pos >= bufferLength) { 81 return -1; 82 } 83 return buffer[pos++] & 255; 84 } 85 86 public int read(byte[] b) throws IOException { 87 return read(b, 0, b.length); 88 } 89 90 public int read(byte[] b, int off, int len) throws IOException { 91 if(len == 0) { 92 return 0; 93 } 94 int read = 0; 95 while(len > 0) { 96 int r = readBlock(b, off, len); 97 if(r < 0) { 98 break; 99 } 100 read += r; 101 off += r; 102 len -= r; 103 } 104 return read == 0 ? -1 : read; 105 } 106 107 public int readBlock(byte[] b, int off, int len) throws IOException { 108 fillBuffer(); 109 if(pos >= bufferLength) { 110 return -1; 111 } 112 int max = Math.min(len, bufferLength - pos); 113 max = Math.min(max, b.length - off); 114 System.arraycopy(buffer, pos, b, off, max); 115 pos += max; 116 return max; 117 } 118 119 public void close() throws IOException { 120 in.close(); 121 } 122 123 } 124 | Popular Tags |