DeflateStream.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. delegate int UnmanagedReadOrWrite (IntPtr buffer, int length);
  39. delegate int ReadMethod (byte[] array, int offset, int count);
  40. delegate void WriteMethod (byte[] array, int offset, int count);
  41. Stream base_stream;
  42. CompressionMode mode;
  43. bool leaveOpen;
  44. bool disposed;
  45. UnmanagedReadOrWrite feeder; // This will be passed to unmanaged code and used there
  46. IntPtr z_stream;
  47. byte [] io_buffer;
  48. public DeflateStream (Stream compressedStream, CompressionMode mode) :
  49. this (compressedStream, mode, false, false)
  50. {
  51. }
  52. public DeflateStream (Stream compressedStream, CompressionMode mode, bool leaveOpen) :
  53. this (compressedStream, mode, leaveOpen, false)
  54. {
  55. }
  56. internal DeflateStream (Stream compressedStream, CompressionMode mode, bool leaveOpen, bool gzip)
  57. {
  58. if (compressedStream == null)
  59. throw new ArgumentNullException ("compressedStream");
  60. if (mode != CompressionMode.Compress && mode != CompressionMode.Decompress)
  61. throw new ArgumentException ("mode");
  62. this.base_stream = compressedStream;
  63. this.feeder = (mode == CompressionMode.Compress) ? new UnmanagedReadOrWrite (UnmanagedWrite) :
  64. new UnmanagedReadOrWrite (UnmanagedRead);
  65. this.z_stream = CreateZStream (mode, gzip, feeder);
  66. if (z_stream == IntPtr.Zero) {
  67. this.base_stream = null;
  68. this.feeder = null;
  69. throw new NotImplementedException ("Failed to initialize zlib. You probably have an old zlib installed. Version 1.2.0.4 or later is required.");
  70. }
  71. this.mode = mode;
  72. this.leaveOpen = leaveOpen;
  73. }
  74. protected override void Dispose (bool disposing)
  75. {
  76. if (disposing && !disposed) {
  77. disposed = true;
  78. IntPtr zz = z_stream;
  79. z_stream = IntPtr.Zero;
  80. int res = 0;
  81. if (zz != IntPtr.Zero)
  82. res = CloseZStream (zz); // This will Flush() the remaining output if any
  83. io_buffer = null;
  84. if (!leaveOpen) {
  85. Stream st = base_stream;
  86. if (st != null)
  87. st.Close ();
  88. base_stream = null;
  89. }
  90. CheckResult (res, "Dispose");
  91. }
  92. base.Dispose (disposing);
  93. }
  94. int UnmanagedRead (IntPtr buffer, int length)
  95. {
  96. int total = 0;
  97. int n = 1;
  98. while (length > 0 && n > 0) {
  99. if (io_buffer == null)
  100. io_buffer = new byte [4096];
  101. n = base_stream.Read (io_buffer, 0, io_buffer.Length);
  102. if (n > 0) {
  103. Marshal.Copy (io_buffer, 0, buffer, n);
  104. unsafe {
  105. buffer = new IntPtr ((byte *) buffer.ToPointer () + n);
  106. }
  107. length -= n;
  108. total += n;
  109. }
  110. }
  111. return total;
  112. }
  113. int UnmanagedWrite (IntPtr buffer, int length)
  114. {
  115. int total = 0;
  116. while (length > 0) {
  117. if (io_buffer == null)
  118. io_buffer = new byte [4096];
  119. int count = Math.Min (length, io_buffer.Length);
  120. Marshal.Copy (buffer, io_buffer, 0, count);
  121. base_stream.Write (io_buffer, 0, count);
  122. unsafe {
  123. buffer = new IntPtr ((byte *) buffer.ToPointer () + count);
  124. }
  125. length -= count;
  126. total += count;
  127. }
  128. return total;
  129. }
  130. unsafe int ReadInternal (byte[] array, int offset, int count)
  131. {
  132. int result = 0;
  133. fixed (byte *b = array) {
  134. IntPtr ptr = new IntPtr (b + offset);
  135. result = ReadZStream (z_stream, ptr, count);
  136. }
  137. CheckResult (result, "ReadInternal");
  138. return result;
  139. }
  140. public override int Read (byte[] dest, int dest_offset, int count)
  141. {
  142. if (disposed)
  143. throw new ObjectDisposedException (GetType ().FullName);
  144. if (dest == null)
  145. throw new ArgumentNullException ("Destination array is null.");
  146. if (!CanRead)
  147. throw new InvalidOperationException ("Stream does not support reading.");
  148. int len = dest.Length;
  149. if (dest_offset < 0 || count < 0)
  150. throw new ArgumentException ("Dest or count is negative.");
  151. if (dest_offset > len)
  152. throw new ArgumentException ("destination offset is beyond array size");
  153. if ((dest_offset + count) > len)
  154. throw new ArgumentException ("Reading would overrun buffer");
  155. return ReadInternal (dest, dest_offset, count);
  156. }
  157. unsafe void WriteInternal (byte[] array, int offset, int count)
  158. {
  159. int result = 0;
  160. fixed (byte *b = array) {
  161. IntPtr ptr = new IntPtr (b + offset);
  162. result = WriteZStream (z_stream, ptr, count);
  163. }
  164. CheckResult (result, "WriteInternal");
  165. }
  166. public override void Write (byte[] src, int src_offset, int count)
  167. {
  168. if (disposed)
  169. throw new ObjectDisposedException (GetType ().FullName);
  170. if (src == null)
  171. throw new ArgumentNullException ("src");
  172. if (src_offset < 0)
  173. throw new ArgumentOutOfRangeException ("src_offset");
  174. if (count < 0)
  175. throw new ArgumentOutOfRangeException ("count");
  176. if (!CanWrite)
  177. throw new NotSupportedException ("Stream does not support writing");
  178. WriteInternal (src, src_offset, count);
  179. }
  180. static void CheckResult (int result, string where)
  181. {
  182. if (result >= 0)
  183. return;
  184. string error;
  185. switch (result) {
  186. case -1: // Z_ERRNO
  187. error = "Unknown error"; // Marshal.GetLastWin32() ?
  188. break;
  189. case -2: // Z_STREAM_ERROR
  190. error = "Internal error";
  191. break;
  192. case -3: // Z_DATA_ERROR
  193. error = "Corrupted data";
  194. break;
  195. case -4: // Z_MEM_ERROR
  196. error = "Not enough memory";
  197. break;
  198. case -5: // Z_BUF_ERROR
  199. error = "Internal error (no progress possible)";
  200. break;
  201. case -6: // Z_VERSION_ERROR
  202. error = "Invalid version";
  203. break;
  204. case -10:
  205. error = "Invalid argument(s)";
  206. break;
  207. case -11:
  208. error = "IO error";
  209. break;
  210. default:
  211. error = "Unknown error";
  212. break;
  213. }
  214. throw new IOException (error + " " + where);
  215. }
  216. public override void Flush ()
  217. {
  218. if (disposed)
  219. throw new ObjectDisposedException (GetType ().FullName);
  220. if (CanWrite) {
  221. int result = Flush (z_stream);
  222. CheckResult (result, "Flush");
  223. }
  224. }
  225. public override IAsyncResult BeginRead (byte [] buffer, int offset, int count,
  226. AsyncCallback cback, object state)
  227. {
  228. if (disposed)
  229. throw new ObjectDisposedException (GetType ().FullName);
  230. if (!CanRead)
  231. throw new NotSupportedException ("This stream does not support reading");
  232. if (buffer == null)
  233. throw new ArgumentNullException ("buffer");
  234. if (count < 0)
  235. throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
  236. if (offset < 0)
  237. throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
  238. if (count + offset > buffer.Length)
  239. throw new ArgumentException ("Buffer too small. count/offset wrong.");
  240. ReadMethod r = new ReadMethod (ReadInternal);
  241. return r.BeginInvoke (buffer, offset, count, cback, state);
  242. }
  243. public override IAsyncResult BeginWrite (byte [] buffer, int offset, int count,
  244. AsyncCallback cback, object state)
  245. {
  246. if (disposed)
  247. throw new ObjectDisposedException (GetType ().FullName);
  248. if (!CanWrite)
  249. throw new InvalidOperationException ("This stream does not support writing");
  250. if (buffer == null)
  251. throw new ArgumentNullException ("buffer");
  252. if (count < 0)
  253. throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
  254. if (offset < 0)
  255. throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
  256. if (count + offset > buffer.Length)
  257. throw new ArgumentException ("Buffer too small. count/offset wrong.");
  258. WriteMethod w = new WriteMethod (WriteInternal);
  259. return w.BeginInvoke (buffer, offset, count, cback, state);
  260. }
  261. public override int EndRead(IAsyncResult async_result)
  262. {
  263. if (async_result == null)
  264. throw new ArgumentNullException ("async_result");
  265. AsyncResult ares = async_result as AsyncResult;
  266. if (ares == null)
  267. throw new ArgumentException ("Invalid IAsyncResult", "async_result");
  268. ReadMethod r = ares.AsyncDelegate as ReadMethod;
  269. if (r == null)
  270. throw new ArgumentException ("Invalid IAsyncResult", "async_result");
  271. return r.EndInvoke (async_result);
  272. }
  273. public override void EndWrite (IAsyncResult async_result)
  274. {
  275. if (async_result == null)
  276. throw new ArgumentNullException ("async_result");
  277. AsyncResult ares = async_result as AsyncResult;
  278. if (ares == null)
  279. throw new ArgumentException ("Invalid IAsyncResult", "async_result");
  280. WriteMethod w = ares.AsyncDelegate as WriteMethod;
  281. if (w == null)
  282. throw new ArgumentException ("Invalid IAsyncResult", "async_result");
  283. w.EndInvoke (async_result);
  284. return;
  285. }
  286. public override long Seek (long offset, SeekOrigin origin)
  287. {
  288. throw new NotSupportedException();
  289. }
  290. public override void SetLength (long value)
  291. {
  292. throw new NotSupportedException();
  293. }
  294. public Stream BaseStream {
  295. get { return base_stream; }
  296. }
  297. public override bool CanRead {
  298. get { return !disposed && mode == CompressionMode.Decompress && base_stream.CanRead; }
  299. }
  300. public override bool CanSeek {
  301. get { return false; }
  302. }
  303. public override bool CanWrite {
  304. get { return !disposed && mode == CompressionMode.Compress && base_stream.CanWrite; }
  305. }
  306. public override long Length {
  307. get { throw new NotSupportedException(); }
  308. }
  309. public override long Position {
  310. get { throw new NotSupportedException(); }
  311. set { throw new NotSupportedException(); }
  312. }
  313. [DllImport ("MonoPosixHelper")]
  314. static extern IntPtr CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder);
  315. [DllImport ("MonoPosixHelper")]
  316. static extern int CloseZStream (IntPtr stream);
  317. [DllImport ("MonoPosixHelper")]
  318. static extern int Flush (IntPtr stream);
  319. [DllImport ("MonoPosixHelper")]
  320. static extern int ReadZStream (IntPtr stream, IntPtr buffer, int length);
  321. [DllImport ("MonoPosixHelper")]
  322. static extern int WriteZStream (IntPtr stream, IntPtr buffer, int length);
  323. }
  324. }
  325. #endif