1 /* -*- Mode: csharp; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
6 // Christopher James Lahey <clahey@ximian.com>
7 // Gonzalo Paniagua Javier (gonzalo@novell.com)
8 // Marek Safar (marek.safar@gmail.com)
10 // (c) Copyright 2004,2009 Novell, Inc. <http://www.novell.com>
11 // Copyright (C) 2013 Xamarin Inc (http://www.xamarin.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 using System.Runtime.InteropServices;
36 using System.Runtime.Remoting.Messaging;
38 namespace System.IO.Compression
40 public class DeflateStream : Stream
42 delegate int ReadMethod (byte[] array, int offset, int count);
43 delegate void WriteMethod (byte[] array, int offset, int count);
49 DeflateStreamNative native;
51 public DeflateStream (Stream stream, CompressionMode mode) :
52 this (stream, mode, false, false)
56 public DeflateStream (Stream stream, CompressionMode mode, bool leaveOpen) :
57 this (stream, mode, leaveOpen, false)
61 internal DeflateStream (Stream stream, CompressionMode mode, bool leaveOpen, int windowsBits) :
62 this (stream, mode, leaveOpen, true)
66 internal DeflateStream (Stream compressedStream, CompressionMode mode, bool leaveOpen, bool gzip)
68 if (compressedStream == null)
69 throw new ArgumentNullException ("compressedStream");
71 if (mode != CompressionMode.Compress && mode != CompressionMode.Decompress)
72 throw new ArgumentException ("mode");
74 this.base_stream = compressedStream;
76 this.native = DeflateStreamNative.Create (compressedStream, mode, gzip);
77 if (this.native == null) {
78 throw new NotImplementedException ("Failed to initialize zlib. You probably have an old zlib installed. Version 1.2.0.4 or later is required.");
81 this.leaveOpen = leaveOpen;
84 public DeflateStream (Stream stream, CompressionLevel compressionLevel)
85 : this (stream, compressionLevel, false, false)
89 public DeflateStream (Stream stream, CompressionLevel compressionLevel, bool leaveOpen)
90 : this (stream, compressionLevel, leaveOpen, false)
94 internal DeflateStream (Stream stream, CompressionLevel compressionLevel, bool leaveOpen, int windowsBits)
95 : this (stream, compressionLevel, leaveOpen, true)
99 internal DeflateStream (Stream stream, CompressionLevel compressionLevel, bool leaveOpen, bool gzip)
100 : this (stream, CompressionMode.Compress, leaveOpen, gzip)
104 protected override void Dispose (bool disposing)
106 native.Dispose (disposing);
108 if (disposing && !disposed) {
112 Stream st = base_stream;
119 base.Dispose (disposing);
122 unsafe int ReadInternal (byte[] array, int offset, int count)
127 fixed (byte *b = array) {
128 IntPtr ptr = new IntPtr (b + offset);
129 return native.ReadZStream (ptr, count);
133 public override int Read (byte[] array, int offset, int count)
136 throw new ObjectDisposedException (GetType ().FullName);
138 throw new ArgumentNullException ("Destination array is null.");
140 throw new InvalidOperationException ("Stream does not support reading.");
141 int len = array.Length;
142 if (offset < 0 || count < 0)
143 throw new ArgumentException ("Dest or count is negative.");
145 throw new ArgumentException ("destination offset is beyond array size");
146 if ((offset + count) > len)
147 throw new ArgumentException ("Reading would overrun buffer");
149 return ReadInternal (array, offset, count);
152 unsafe void WriteInternal (byte[] array, int offset, int count)
157 fixed (byte *b = array) {
158 IntPtr ptr = new IntPtr (b + offset);
159 native.WriteZStream (ptr, count);
163 public override void Write (byte[] array, int offset, int count)
166 throw new ObjectDisposedException (GetType ().FullName);
169 throw new ArgumentNullException ("array");
172 throw new ArgumentOutOfRangeException ("offset");
175 throw new ArgumentOutOfRangeException ("count");
178 throw new NotSupportedException ("Stream does not support writing");
180 if (offset > array.Length - count)
181 throw new ArgumentException ("Buffer too small. count/offset wrong.");
183 WriteInternal (array, offset, count);
186 public override void Flush ()
189 throw new ObjectDisposedException (GetType ().FullName);
196 public override IAsyncResult BeginRead (byte [] array, int offset, int count,
197 AsyncCallback asyncCallback, object asyncState)
200 throw new ObjectDisposedException (GetType ().FullName);
203 throw new NotSupportedException ("This stream does not support reading");
206 throw new ArgumentNullException ("array");
209 throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
212 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
214 if (count + offset > array.Length)
215 throw new ArgumentException ("Buffer too small. count/offset wrong.");
217 ReadMethod r = new ReadMethod (ReadInternal);
218 return r.BeginInvoke (array, offset, count, asyncCallback, asyncState);
221 public override IAsyncResult BeginWrite (byte [] array, int offset, int count,
222 AsyncCallback asyncCallback, object asyncState)
225 throw new ObjectDisposedException (GetType ().FullName);
228 throw new InvalidOperationException ("This stream does not support writing");
231 throw new ArgumentNullException ("array");
234 throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
237 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
239 if (count + offset > array.Length)
240 throw new ArgumentException ("Buffer too small. count/offset wrong.");
242 WriteMethod w = new WriteMethod (WriteInternal);
243 return w.BeginInvoke (array, offset, count, asyncCallback, asyncState);
246 public override int EndRead(IAsyncResult asyncResult)
248 if (asyncResult == null)
249 throw new ArgumentNullException ("asyncResult");
251 AsyncResult ares = asyncResult as AsyncResult;
253 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
255 ReadMethod r = ares.AsyncDelegate as ReadMethod;
257 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
259 return r.EndInvoke (asyncResult);
262 public override void EndWrite (IAsyncResult asyncResult)
264 if (asyncResult == null)
265 throw new ArgumentNullException ("asyncResult");
267 AsyncResult ares = asyncResult as AsyncResult;
269 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
271 WriteMethod w = ares.AsyncDelegate as WriteMethod;
273 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
275 w.EndInvoke (asyncResult);
279 public override long Seek (long offset, SeekOrigin origin)
281 throw new NotSupportedException();
284 public override void SetLength (long value)
286 throw new NotSupportedException();
289 public Stream BaseStream {
290 get { return base_stream; }
293 public override bool CanRead {
294 get { return !disposed && mode == CompressionMode.Decompress && base_stream.CanRead; }
297 public override bool CanSeek {
298 get { return false; }
301 public override bool CanWrite {
302 get { return !disposed && mode == CompressionMode.Compress && base_stream.CanWrite; }
305 public override long Length {
306 get { throw new NotSupportedException(); }
309 public override long Position {
310 get { throw new NotSupportedException(); }
311 set { throw new NotSupportedException(); }
315 class DeflateStreamNative
317 const int BufferSize = 4096;
319 [UnmanagedFunctionPointer (CallingConvention.Cdecl)]
320 delegate int UnmanagedReadOrWrite (IntPtr buffer, int length, IntPtr data);
322 UnmanagedReadOrWrite feeder; // This will be passed to unmanaged code and used there
330 private DeflateStreamNative ()
334 public static DeflateStreamNative Create (Stream compressedStream, CompressionMode mode, bool gzip)
336 var dsn = new DeflateStreamNative ();
337 dsn.data = GCHandle.Alloc (dsn);
338 dsn.feeder = mode == CompressionMode.Compress ? new UnmanagedReadOrWrite (UnmanagedWrite) : new UnmanagedReadOrWrite (UnmanagedRead);
339 dsn.z_stream = CreateZStream (mode, gzip, dsn.feeder, GCHandle.ToIntPtr (dsn.data));
340 if (dsn.z_stream == IntPtr.Zero) {
345 dsn.base_stream = compressedStream;
349 ~DeflateStreamNative ()
354 public void Dispose (bool disposing)
356 if (disposing && !disposed) {
358 GC.SuppressFinalize (this);
362 IntPtr zz = z_stream;
363 z_stream = IntPtr.Zero;
364 if (zz != IntPtr.Zero)
365 CloseZStream (zz); // This will Flush() the remaining output if any
368 if (data.IsAllocated) {
375 var res = Flush (z_stream);
376 CheckResult (res, "Flush");
379 public int ReadZStream (IntPtr buffer, int length)
381 var res = ReadZStream (z_stream, buffer, length);
382 CheckResult (res, "ReadInternal");
386 public void WriteZStream (IntPtr buffer, int length)
388 var res = WriteZStream (z_stream, buffer, length);
389 CheckResult (res, "WriteInternal");
392 [Mono.Util.MonoPInvokeCallback (typeof (UnmanagedReadOrWrite))]
393 static int UnmanagedRead (IntPtr buffer, int length, IntPtr data)
395 GCHandle s = GCHandle.FromIntPtr (data);
396 var self = s.Target as DeflateStreamNative;
399 return self.UnmanagedRead (buffer, length);
402 int UnmanagedRead (IntPtr buffer, int length)
404 if (io_buffer == null)
405 io_buffer = new byte [BufferSize];
407 int count = Math.Min (length, io_buffer.Length);
408 int n = base_stream.Read (io_buffer, 0, count);
410 Marshal.Copy (io_buffer, 0, buffer, n);
415 [Mono.Util.MonoPInvokeCallback (typeof (UnmanagedReadOrWrite))]
416 static int UnmanagedWrite (IntPtr buffer, int length, IntPtr data)
418 GCHandle s = GCHandle.FromIntPtr (data);
419 var self = s.Target as DeflateStreamNative;
422 return self.UnmanagedWrite (buffer, length);
425 int UnmanagedWrite (IntPtr buffer, int length)
429 if (io_buffer == null)
430 io_buffer = new byte [BufferSize];
432 int count = Math.Min (length, io_buffer.Length);
433 Marshal.Copy (buffer, io_buffer, 0, count);
434 base_stream.Write (io_buffer, 0, count);
436 buffer = new IntPtr ((byte *) buffer.ToPointer () + count);
444 static void CheckResult (int result, string where)
452 error = "Unknown error"; // Marshal.GetLastWin32() ?
454 case -2: // Z_STREAM_ERROR
455 error = "Internal error";
457 case -3: // Z_DATA_ERROR
458 error = "Corrupted data";
460 case -4: // Z_MEM_ERROR
461 error = "Not enough memory";
463 case -5: // Z_BUF_ERROR
464 error = "Internal error (no progress possible)";
466 case -6: // Z_VERSION_ERROR
467 error = "Invalid version";
470 error = "Invalid argument(s)";
476 error = "Unknown error";
480 throw new IOException (error + " " + where);
483 #if MONOTOUCH || MONODROID
484 const string LIBNAME = "__Internal";
486 const string LIBNAME = "MonoPosixHelper";
490 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
491 static extern IntPtr CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder, IntPtr data);
493 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
494 static extern int CloseZStream (IntPtr stream);
496 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
497 static extern int Flush (IntPtr stream);
499 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
500 static extern int ReadZStream (IntPtr stream, IntPtr buffer, int length);
502 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
503 static extern int WriteZStream (IntPtr stream, IntPtr buffer, int length);
505 static IntPtr CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder, IntPtr data)
507 throw new PlatformNotSupportedException ();
510 static int CloseZStream (IntPtr stream)
512 throw new PlatformNotSupportedException ();
515 static int Flush (IntPtr stream)
517 throw new PlatformNotSupportedException ();
520 static int ReadZStream (IntPtr stream, IntPtr buffer, int length)
522 throw new PlatformNotSupportedException ();
525 static int WriteZStream (IntPtr stream, IntPtr buffer, int length)
527 throw new PlatformNotSupportedException ();