DeflateStream.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. /* -*- Mode: csharp; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
  2. //
  3. // DeflateStream.cs
  4. //
  5. // Authors:
  6. // Christopher James Lahey <[email protected]>
  7. // Gonzalo Paniagua Javier ([email protected])
  8. //
  9. // (c) Copyright 2004,2009 Novell, Inc. <http://www.novell.com>
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. #if NET_2_0
  31. using System;
  32. using System.IO;
  33. using System.Runtime.InteropServices;
  34. using System.Runtime.Remoting.Messaging;
  35. namespace System.IO.Compression {
  36. public class DeflateStream : Stream
  37. {
  38. const int BufferSize = 4096;
  39. delegate int UnmanagedReadOrWrite (IntPtr buffer, int length);
  40. delegate int ReadMethod (byte[] array, int offset, int count);
  41. delegate void WriteMethod (byte[] array, int offset, int count);
  42. Stream base_stream;
  43. CompressionMode mode;
  44. bool leaveOpen;
  45. bool disposed;
  46. UnmanagedReadOrWrite feeder; // This will be passed to unmanaged code and used there
  47. IntPtr z_stream;
  48. byte [] io_buffer;
  49. public DeflateStream (Stream compressedStream, CompressionMode mode) :
  50. this (compressedStream, mode, false, false)
  51. {
  52. }
  53. public DeflateStream (Stream compressedStream, CompressionMode mode, bool leaveOpen) :
  54. this (compressedStream, mode, leaveOpen, false)
  55. {
  56. }
  57. internal DeflateStream (Stream compressedStream, CompressionMode mode, bool leaveOpen, bool gzip)
  58. {
  59. if (compressedStream == null)
  60. throw new ArgumentNullException ("compressedStream");
  61. if (mode != CompressionMode.Compress && mode != CompressionMode.Decompress)
  62. throw new ArgumentException ("mode");
  63. this.base_stream = compressedStream;
  64. this.feeder = (mode == CompressionMode.Compress) ? new UnmanagedReadOrWrite (UnmanagedWrite) :
  65. new UnmanagedReadOrWrite (UnmanagedRead);
  66. this.z_stream = CreateZStream (mode, gzip, feeder);
  67. if (z_stream == IntPtr.Zero) {
  68. this.base_stream = null;
  69. this.feeder = null;
  70. throw new NotImplementedException ("Failed to initialize zlib. You probably have an old zlib installed. Version 1.2.0.4 or later is required.");
  71. }
  72. this.mode = mode;
  73. this.leaveOpen = leaveOpen;
  74. }
  75. protected override void Dispose (bool disposing)
  76. {
  77. if (disposing && !disposed) {
  78. disposed = true;
  79. IntPtr zz = z_stream;
  80. z_stream = IntPtr.Zero;
  81. int res = 0;
  82. if (zz != IntPtr.Zero)
  83. res = CloseZStream (zz); // This will Flush() the remaining output if any
  84. io_buffer = null;
  85. if (!leaveOpen) {
  86. Stream st = base_stream;
  87. if (st != null)
  88. st.Close ();
  89. base_stream = null;
  90. }
  91. CheckResult (res, "Dispose");
  92. }
  93. base.Dispose (disposing);
  94. }
  95. int UnmanagedRead (IntPtr buffer, int length)
  96. {
  97. int total = 0;
  98. int n = 1;
  99. while (length > 0 && n > 0) {
  100. if (io_buffer == null)
  101. io_buffer = new byte [BufferSize];
  102. int count = Math.Min (length, io_buffer.Length);
  103. n = base_stream.Read (io_buffer, 0, count);
  104. if (n > 0) {
  105. Marshal.Copy (io_buffer, 0, buffer, n);
  106. unsafe {
  107. buffer = new IntPtr ((byte *) buffer.ToPointer () + n);
  108. }
  109. length -= n;
  110. total += n;
  111. }
  112. }
  113. return total;
  114. }
  115. int UnmanagedWrite (IntPtr buffer, int length)
  116. {
  117. int total = 0;
  118. while (length > 0) {
  119. if (io_buffer == null)
  120. io_buffer = new byte [BufferSize];
  121. int count = Math.Min (length, io_buffer.Length);
  122. Marshal.Copy (buffer, io_buffer, 0, count);
  123. base_stream.Write (io_buffer, 0, count);
  124. unsafe {
  125. buffer = new IntPtr ((byte *) buffer.ToPointer () + count);
  126. }
  127. length -= count;
  128. total += count;
  129. }
  130. return total;
  131. }
  132. unsafe int ReadInternal (byte[] array, int offset, int count)
  133. {
  134. int result = 0;
  135. fixed (byte *b = array) {
  136. IntPtr ptr = new IntPtr (b + offset);
  137. result = ReadZStream (z_stream, ptr, count);
  138. }
  139. CheckResult (result, "ReadInternal");
  140. return result;
  141. }
  142. public override int Read (byte[] dest, int dest_offset, int count)
  143. {
  144. if (disposed)
  145. throw new ObjectDisposedException (GetType ().FullName);
  146. if (dest == null)
  147. throw new ArgumentNullException ("Destination array is null.");
  148. if (!CanRead)
  149. throw new InvalidOperationException ("Stream does not support reading.");
  150. int len = dest.Length;
  151. if (dest_offset < 0 || count < 0)
  152. throw new ArgumentException ("Dest or count is negative.");
  153. if (dest_offset > len)
  154. throw new ArgumentException ("destination offset is beyond array size");
  155. if ((dest_offset + count) > len)
  156. throw new ArgumentException ("Reading would overrun buffer");
  157. return ReadInternal (dest, dest_offset, count);
  158. }
  159. unsafe void WriteInternal (byte[] array, int offset, int count)
  160. {
  161. int result = 0;
  162. fixed (byte *b = array) {
  163. IntPtr ptr = new IntPtr (b + offset);
  164. result = WriteZStream (z_stream, ptr, count);
  165. }
  166. CheckResult (result, "WriteInternal");
  167. }
  168. public override void Write (byte[] src, int src_offset, int count)
  169. {
  170. if (disposed)
  171. throw new ObjectDisposedException (GetType ().FullName);
  172. if (src == null)
  173. throw new ArgumentNullException ("src");
  174. if (src_offset < 0)
  175. throw new ArgumentOutOfRangeException ("src_offset");
  176. if (count < 0)
  177. throw new ArgumentOutOfRangeException ("count");
  178. if (!CanWrite)
  179. throw new NotSupportedException ("Stream does not support writing");
  180. WriteInternal (src, src_offset, count);
  181. }
  182. static void CheckResult (int result, string where)
  183. {
  184. if (result >= 0)
  185. return;
  186. string error;
  187. switch (result) {
  188. case -1: // Z_ERRNO
  189. error = "Unknown error"; // Marshal.GetLastWin32() ?
  190. break;
  191. case -2: // Z_STREAM_ERROR
  192. error = "Internal error";
  193. break;
  194. case -3: // Z_DATA_ERROR
  195. error = "Corrupted data";
  196. break;
  197. case -4: // Z_MEM_ERROR
  198. error = "Not enough memory";
  199. break;
  200. case -5: // Z_BUF_ERROR
  201. error = "Internal error (no progress possible)";
  202. break;
  203. case -6: // Z_VERSION_ERROR
  204. error = "Invalid version";
  205. break;
  206. case -10:
  207. error = "Invalid argument(s)";
  208. break;
  209. case -11:
  210. error = "IO error";
  211. break;
  212. default:
  213. error = "Unknown error";
  214. break;
  215. }
  216. throw new IOException (error + " " + where);
  217. }
  218. public override void Flush ()
  219. {
  220. if (disposed)
  221. throw new ObjectDisposedException (GetType ().FullName);
  222. if (CanWrite) {
  223. int result = Flush (z_stream);
  224. CheckResult (result, "Flush");
  225. }
  226. }
  227. public override IAsyncResult BeginRead (byte [] buffer, int offset, int count,
  228. AsyncCallback cback, object state)
  229. {
  230. if (disposed)
  231. throw new ObjectDisposedException (GetType ().FullName);
  232. if (!CanRead)
  233. throw new NotSupportedException ("This stream does not support reading");
  234. if (buffer == null)
  235. throw new ArgumentNullException ("buffer");
  236. if (count < 0)
  237. throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
  238. if (offset < 0)
  239. throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
  240. if (count + offset > buffer.Length)
  241. throw new ArgumentException ("Buffer too small. count/offset wrong.");
  242. ReadMethod r = new ReadMethod (ReadInternal);
  243. return r.BeginInvoke (buffer, offset, count, cback, state);
  244. }
  245. public override IAsyncResult BeginWrite (byte [] buffer, int offset, int count,
  246. AsyncCallback cback, object state)
  247. {
  248. if (disposed)
  249. throw new ObjectDisposedException (GetType ().FullName);
  250. if (!CanWrite)
  251. throw new InvalidOperationException ("This stream does not support writing");
  252. if (buffer == null)
  253. throw new ArgumentNullException ("buffer");
  254. if (count < 0)
  255. throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
  256. if (offset < 0)
  257. throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
  258. if (count + offset > buffer.Length)
  259. throw new ArgumentException ("Buffer too small. count/offset wrong.");
  260. WriteMethod w = new WriteMethod (WriteInternal);
  261. return w.BeginInvoke (buffer, offset, count, cback, state);
  262. }
  263. public override int EndRead(IAsyncResult async_result)
  264. {
  265. if (async_result == null)
  266. throw new ArgumentNullException ("async_result");
  267. AsyncResult ares = async_result as AsyncResult;
  268. if (ares == null)
  269. throw new ArgumentException ("Invalid IAsyncResult", "async_result");
  270. ReadMethod r = ares.AsyncDelegate as ReadMethod;
  271. if (r == null)
  272. throw new ArgumentException ("Invalid IAsyncResult", "async_result");
  273. return r.EndInvoke (async_result);
  274. }
  275. public override void EndWrite (IAsyncResult async_result)
  276. {
  277. if (async_result == null)
  278. throw new ArgumentNullException ("async_result");
  279. AsyncResult ares = async_result as AsyncResult;
  280. if (ares == null)
  281. throw new ArgumentException ("Invalid IAsyncResult", "async_result");
  282. WriteMethod w = ares.AsyncDelegate as WriteMethod;
  283. if (w == null)
  284. throw new ArgumentException ("Invalid IAsyncResult", "async_result");
  285. w.EndInvoke (async_result);
  286. return;
  287. }
  288. public override long Seek (long offset, SeekOrigin origin)
  289. {
  290. throw new NotSupportedException();
  291. }
  292. public override void SetLength (long value)
  293. {
  294. throw new NotSupportedException();
  295. }
  296. public Stream BaseStream {
  297. get { return base_stream; }
  298. }
  299. public override bool CanRead {
  300. get { return !disposed && mode == CompressionMode.Decompress && base_stream.CanRead; }
  301. }
  302. public override bool CanSeek {
  303. get { return false; }
  304. }
  305. public override bool CanWrite {
  306. get { return !disposed && mode == CompressionMode.Compress && base_stream.CanWrite; }
  307. }
  308. public override long Length {
  309. get { throw new NotSupportedException(); }
  310. }
  311. public override long Position {
  312. get { throw new NotSupportedException(); }
  313. set { throw new NotSupportedException(); }
  314. }
  315. [DllImport ("MonoPosixHelper")]
  316. static extern IntPtr CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder);
  317. [DllImport ("MonoPosixHelper")]
  318. static extern int CloseZStream (IntPtr stream);
  319. [DllImport ("MonoPosixHelper")]
  320. static extern int Flush (IntPtr stream);
  321. [DllImport ("MonoPosixHelper")]
  322. static extern int ReadZStream (IntPtr stream, IntPtr buffer, int length);
  323. [DllImport ("MonoPosixHelper")]
  324. static extern int WriteZStream (IntPtr stream, IntPtr buffer, int length);
  325. }
  326. }
  327. #endif