1 /** 2 * Authors: kntroh <knt.roh@gmail.com> 3 */ 4 module java.util.zip.DeflaterOutputStream; 5 6 version (Tango) { 7 version (Windows) { 8 pragma (lib, "zlib.lib"); 9 } else { 10 pragma (lib, "zlib"); 11 } 12 13 import tango.io.stream.Zlib; 14 import tango.io.model.IConduit; 15 16 class OutputStreamWrapper : tango.io.model.IConduit.OutputStream { 17 18 java.io.OutputStream.OutputStream _ostr; 19 20 this (java.io.OutputStream.OutputStream ostr) { 21 _ostr = ostr; 22 } 23 24 override 25 size_t write (void[] src) { 26 _ostr.write(cast(byte[]) src); 27 return src.length; 28 } 29 override 30 IOStream flush() { 31 _ostr.flush(); 32 return this; 33 } 34 override 35 void close() { 36 _ostr.close(); 37 } 38 39 override 40 long seek(long offset, Anchor anchor = Anchor.Begin) { 41 implMissing(__FILE__,__LINE__); 42 return 0; 43 } 44 override 45 IConduit conduit() { 46 implMissing(__FILE__,__LINE__); 47 return null; 48 } 49 override 50 OutputStream copy(tango.io.model.IConduit.InputStream src, size_t max = -1) { 51 implMissing(__FILE__,__LINE__); 52 return null; 53 } 54 override 55 OutputStream output() { 56 implMissing(__FILE__,__LINE__); 57 return null; 58 } 59 } 60 } else { // Phobos 61 import std.zlib; 62 } 63 64 import java.lang.all; 65 66 class DeflaterOutputStream : java.io.OutputStream.OutputStream { 67 68 version (Tango) { 69 private ZlibOutput _ostr; 70 } else { // Phobos 71 private java.io.OutputStream.OutputStream _ostr; 72 private Compress _compress; 73 } 74 75 protected byte[] buf; 76 77 this (java.io.OutputStream.OutputStream ostr) { 78 version (Tango) { 79 _ostr = new ZlibOutput(new OutputStreamWrapper(ostr)); 80 } else { // Phobos 81 _ostr = ostr; 82 _compress = new Compress(); 83 } 84 } 85 86 protected void deflate() { 87 version (Tango) { 88 _ostr.write(buf); 89 } else { // Phobos 90 auto bytes = _compress.compress(buf); 91 if (0 < bytes.length) { 92 _ostr.write(cast(byte[]) bytes); 93 } 94 } 95 buf.length = 0; 96 } 97 98 void finish() { 99 version (Tango) { 100 _ostr.commit(); 101 } else { // Phobos 102 auto bytes = _compress.flush(Z_FINISH); 103 if (0 < bytes.length) { 104 _ostr.write(cast(byte[]) bytes); 105 _ostr.flush(); 106 } 107 } 108 } 109 110 override 111 public void write(int b) { 112 byte[1] bytes; 113 bytes[0] = cast(byte) (b & 0xFF); 114 write(bytes, 0, bytes.length); 115 } 116 117 override 118 public void write(in byte[] b) { 119 write(b, 0, cast(int)b.length); 120 } 121 122 override 123 void write(in byte[] b, ptrdiff_t off, ptrdiff_t len) { 124 buf ~= b[off .. off + len]; 125 deflate(); 126 } 127 128 override 129 void flush() { 130 deflate(); 131 _ostr.flush(); 132 } 133 134 override 135 void close() { 136 finish(); 137 _ostr.close(); 138 } 139 }