DeflateStream.cs 12 KB

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