1 30 package org.jruby.util; 31 32 import java.io.IOException ; 33 import java.io.UnsupportedEncodingException ; 34 import java.util.zip.DataFormatException ; 35 import java.util.zip.Deflater ; 36 37 import org.jruby.Ruby; 38 import org.jruby.RubyString; 39 import org.jruby.runtime.builtin.IRubyObject; 40 41 public class ZlibDeflate { 42 private Deflater flater; 43 private ByteList collected; 44 private Ruby runtime; 45 46 public static final int BASE_SIZE = 100; 47 48 public final static int DEF_MEM_LEVEL = 8; 49 public final static int MAX_MEM_LEVEL = 9; 50 51 public final static int MAX_WBITS = 15; 52 53 public final static int NO_FLUSH = 0; 54 public final static int SYNC_FLUSH = 2; 55 public final static int FULL_FLUSH = 3; 56 public final static int FINISH = 4; 57 58 public ZlibDeflate(IRubyObject caller, int level, int win_bits, int memlevel, int strategy) { 59 super(); 60 flater = new Deflater (level,false); 61 flater.setStrategy(strategy); 62 collected = new ByteList(BASE_SIZE); 63 runtime = caller.getRuntime(); 64 } 65 66 public static IRubyObject s_deflate(IRubyObject caller, ByteList str, int level) 67 throws DataFormatException , IOException { 68 ZlibDeflate zstream = new ZlibDeflate(caller, level, MAX_WBITS, DEF_MEM_LEVEL, Deflater.DEFAULT_STRATEGY); 69 IRubyObject result = zstream.deflate(str, FINISH); 70 zstream.close(); 71 return result; 72 } 73 74 public Deflater getDeflater() { 75 return flater; 76 } 77 78 public void append(IRubyObject obj) throws IOException , UnsupportedEncodingException { 79 append(obj.convertToString().getByteList()); 80 } 81 82 public void append(ByteList obj) throws IOException { 83 collected.append(obj); 84 } 85 86 public void params(int level, int strategy) { 87 flater.setLevel(level); 88 flater.setStrategy(strategy); 89 } 90 91 public IRubyObject set_dictionary(IRubyObject str) throws UnsupportedEncodingException { 92 flater.setDictionary(str.convertToString().getBytes()); 93 return str; 94 } 95 96 public IRubyObject flush(int flush) throws IOException { 97 return deflate(new ByteList(0), flush); 98 } 99 100 public IRubyObject deflate(ByteList str, int flush) throws IOException { 101 if (null == str) { 102 return finish(); 103 } else { 104 append(str); 105 if (flush == FINISH) { 106 return finish(); 107 } 108 return runtime.newString(""); 109 } 110 } 111 112 public IRubyObject finish() throws IOException { 113 ByteList result = new ByteList(collected.realSize); 114 byte[] outp = new byte[1024]; 115 ByteList buf = collected; 116 collected = new ByteList(BASE_SIZE); 117 flater.setInput(buf.bytes,0,buf.realSize); 118 flater.finish(); 119 int resultLength = -1; 120 while (!flater.finished() && resultLength != 0) { 121 resultLength = flater.deflate(outp); 122 result.append(outp, 0, resultLength); 123 } 124 return RubyString.newString(runtime, result); 125 } 126 127 public void close() { 128 } 129 } 130 | Popular Tags |