1 5 package org.h2.compress; 6 7 import java.io.IOException ; 8 import java.io.OutputStream ; 9 10 import org.h2.engine.Constants; 11 12 public class LZFOutputStream extends OutputStream { 13 14 static final int MAGIC = ('H' << 24) | ('2' << 16) | ('I' << 8) | 'S'; 15 private OutputStream out; 16 private byte[] buffer; 17 private int pos; 18 private byte[] outBuffer; 19 private CompressLZF compress = new CompressLZF(); 20 21 public LZFOutputStream(OutputStream out) throws IOException { 22 this.out = out; 23 int len = Constants.IO_BUFFER_SIZE_COMPRESS; 24 buffer = new byte[len]; 25 ensureOutput(len); 26 writeInt(MAGIC); 27 } 28 29 private void ensureOutput(int len) { 30 int outputLen = (len < 100 ? len + 100 : len) * 2; 32 if(outBuffer == null || outBuffer.length < outputLen) { 33 outBuffer = new byte[outputLen]; 34 } 35 } 36 37 public void write(int b) throws IOException { 38 if(pos >= buffer.length) { 39 flush(); 40 } 41 buffer[pos++] = (byte)b; 42 } 43 44 private void compressAndWrite(byte[] buff, int len) throws IOException { 45 if(len > 0) { 46 ensureOutput(len); 47 int compressed = compress.compress(buff, len, outBuffer, 0); 48 if(compressed > len) { 49 writeInt(-len); 50 out.write(buff, 0, len); 51 } else { 52 writeInt(compressed); 53 writeInt(len); 54 out.write(outBuffer, 0, compressed); 55 } 56 } 57 } 58 59 private void writeInt(int x) throws IOException { 60 out.write((byte) (x >> 24)); 61 out.write((byte) (x >> 16)); 62 out.write((byte) (x >> 8)); 63 out.write((byte) x); 64 } 65 66 public void write(byte[] buff, int off, int len) throws IOException { 67 while(len > 0) { 68 int copy = Math.min(buffer.length - pos, len); 69 System.arraycopy(buff, off, buffer, pos, copy); 70 pos += copy; 71 if(pos >= buffer.length) { 72 flush(); 73 } 74 off += copy; 75 len -= copy; 76 } 77 } 78 79 public void flush() throws IOException { 80 compressAndWrite(buffer, pos); 81 pos = 0; 82 } 83 84 public void close() throws IOException { 85 flush(); 86 out.close(); 87 } 88 89 } 90 | Popular Tags |