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 compressedStream, CompressionMode mode, bool leaveOpen, bool gzip)
63 if (compressedStream == null)
64 throw new ArgumentNullException ("compressedStream");
66 if (mode != CompressionMode.Compress && mode != CompressionMode.Decompress)
67 throw new ArgumentException ("mode");
69 this.base_stream = compressedStream;
71 this.native = DeflateStreamNative.Create (compressedStream, mode, gzip);
72 if (this.native == null) {
73 throw new NotImplementedException ("Failed to initialize zlib. You probably have an old zlib installed. Version 1.2.0.4 or later is required.");
76 this.leaveOpen = leaveOpen;
79 public DeflateStream (Stream stream, CompressionLevel compressionLevel)
80 : this (stream, compressionLevel, false, false)
84 public DeflateStream (Stream stream, CompressionLevel compressionLevel, bool leaveOpen)
85 : this (stream, compressionLevel, leaveOpen, false)
89 internal DeflateStream (Stream stream, CompressionLevel compressionLevel, bool leaveOpen, bool gzip)
90 : this (stream, CompressionMode.Compress, leaveOpen, gzip)
94 protected override void Dispose (bool disposing)
96 native.Dispose (disposing);
98 if (disposing && !disposed) {
102 Stream st = base_stream;
109 base.Dispose (disposing);
112 unsafe int ReadInternal (byte[] array, int offset, int count)
117 fixed (byte *b = array) {
118 IntPtr ptr = new IntPtr (b + offset);
119 return native.ReadZStream (ptr, count);
123 public override int Read (byte[] array, int offset, int count)
126 throw new ObjectDisposedException (GetType ().FullName);
128 throw new ArgumentNullException ("Destination array is null.");
130 throw new InvalidOperationException ("Stream does not support reading.");
131 int len = array.Length;
132 if (offset < 0 || count < 0)
133 throw new ArgumentException ("Dest or count is negative.");
135 throw new ArgumentException ("destination offset is beyond array size");
136 if ((offset + count) > len)
137 throw new ArgumentException ("Reading would overrun buffer");
139 return ReadInternal (array, offset, count);
142 unsafe void WriteInternal (byte[] array, int offset, int count)
147 fixed (byte *b = array) {
148 IntPtr ptr = new IntPtr (b + offset);
149 native.WriteZStream (ptr, count);
153 public override void Write (byte[] array, int offset, int count)
156 throw new ObjectDisposedException (GetType ().FullName);
159 throw new ArgumentNullException ("array");
162 throw new ArgumentOutOfRangeException ("offset");
165 throw new ArgumentOutOfRangeException ("count");
168 throw new NotSupportedException ("Stream does not support writing");
170 if (offset > array.Length - count)
171 throw new ArgumentException ("Buffer too small. count/offset wrong.");
173 WriteInternal (array, offset, count);
176 public override void Flush ()
179 throw new ObjectDisposedException (GetType ().FullName);
186 public override IAsyncResult BeginRead (byte [] buffer, int offset, int count,
187 AsyncCallback cback, object state)
190 throw new ObjectDisposedException (GetType ().FullName);
193 throw new NotSupportedException ("This stream does not support reading");
196 throw new ArgumentNullException ("buffer");
199 throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
202 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
204 if (count + offset > buffer.Length)
205 throw new ArgumentException ("Buffer too small. count/offset wrong.");
207 ReadMethod r = new ReadMethod (ReadInternal);
208 return r.BeginInvoke (buffer, offset, count, cback, state);
211 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int count,
212 AsyncCallback cback, object state)
215 throw new ObjectDisposedException (GetType ().FullName);
218 throw new InvalidOperationException ("This stream does not support writing");
221 throw new ArgumentNullException ("buffer");
224 throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
227 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
229 if (count + offset > buffer.Length)
230 throw new ArgumentException ("Buffer too small. count/offset wrong.");
232 WriteMethod w = new WriteMethod (WriteInternal);
233 return w.BeginInvoke (buffer, offset, count, cback, state);
236 public override int EndRead(IAsyncResult async_result)
238 if (async_result == null)
239 throw new ArgumentNullException ("async_result");
241 AsyncResult ares = async_result as AsyncResult;
243 throw new ArgumentException ("Invalid IAsyncResult", "async_result");
245 ReadMethod r = ares.AsyncDelegate as ReadMethod;
247 throw new ArgumentException ("Invalid IAsyncResult", "async_result");
249 return r.EndInvoke (async_result);
252 public override void EndWrite (IAsyncResult async_result)
254 if (async_result == null)
255 throw new ArgumentNullException ("async_result");
257 AsyncResult ares = async_result as AsyncResult;
259 throw new ArgumentException ("Invalid IAsyncResult", "async_result");
261 WriteMethod w = ares.AsyncDelegate as WriteMethod;
263 throw new ArgumentException ("Invalid IAsyncResult", "async_result");
265 w.EndInvoke (async_result);
269 public override long Seek (long offset, SeekOrigin origin)
271 throw new NotSupportedException();
274 public override void SetLength (long value)
276 throw new NotSupportedException();
279 public Stream BaseStream {
280 get { return base_stream; }
283 public override bool CanRead {
284 get { return !disposed && mode == CompressionMode.Decompress && base_stream.CanRead; }
287 public override bool CanSeek {
288 get { return false; }
291 public override bool CanWrite {
292 get { return !disposed && mode == CompressionMode.Compress && base_stream.CanWrite; }
295 public override long Length {
296 get { throw new NotSupportedException(); }
299 public override long Position {
300 get { throw new NotSupportedException(); }
301 set { throw new NotSupportedException(); }
305 class DeflateStreamNative
307 const int BufferSize = 4096;
309 [UnmanagedFunctionPointer (CallingConvention.Cdecl)]
310 delegate int UnmanagedReadOrWrite (IntPtr buffer, int length, IntPtr data);
312 UnmanagedReadOrWrite feeder; // This will be passed to unmanaged code and used there
320 private DeflateStreamNative ()
324 public static DeflateStreamNative Create (Stream compressedStream, CompressionMode mode, bool gzip)
326 var dsn = new DeflateStreamNative ();
327 dsn.data = GCHandle.Alloc (dsn);
328 dsn.feeder = mode == CompressionMode.Compress ? new UnmanagedReadOrWrite (UnmanagedWrite) : new UnmanagedReadOrWrite (UnmanagedRead);
329 dsn.z_stream = CreateZStream (mode, gzip, dsn.feeder, GCHandle.ToIntPtr (dsn.data));
330 if (dsn.z_stream == IntPtr.Zero) {
335 dsn.base_stream = compressedStream;
339 ~DeflateStreamNative ()
344 public void Dispose (bool disposing)
346 if (disposing && !disposed) {
348 GC.SuppressFinalize (this);
352 IntPtr zz = z_stream;
353 z_stream = IntPtr.Zero;
354 if (zz != IntPtr.Zero)
355 CloseZStream (zz); // This will Flush() the remaining output if any
358 if (data.IsAllocated) {
365 var res = Flush (z_stream);
366 CheckResult (res, "Flush");
369 public int ReadZStream (IntPtr buffer, int length)
371 var res = ReadZStream (z_stream, buffer, length);
372 CheckResult (res, "ReadInternal");
376 public void WriteZStream (IntPtr buffer, int length)
378 var res = WriteZStream (z_stream, buffer, length);
379 CheckResult (res, "WriteInternal");
382 #if MONOTOUCH || FULL_AOT_RUNTIME
383 [Mono.Util.MonoPInvokeCallback (typeof (UnmanagedReadOrWrite))]
385 static int UnmanagedRead (IntPtr buffer, int length, IntPtr data)
387 GCHandle s = GCHandle.FromIntPtr (data);
388 var self = s.Target as DeflateStreamNative;
391 return self.UnmanagedRead (buffer, length);
394 int UnmanagedRead (IntPtr buffer, int length)
396 if (io_buffer == null)
397 io_buffer = new byte [BufferSize];
399 int count = Math.Min (length, io_buffer.Length);
400 int n = base_stream.Read (io_buffer, 0, count);
402 Marshal.Copy (io_buffer, 0, buffer, n);
407 #if MONOTOUCH || FULL_AOT_RUNTIME
408 [Mono.Util.MonoPInvokeCallback (typeof (UnmanagedReadOrWrite))]
410 static int UnmanagedWrite (IntPtr buffer, int length, IntPtr data)
412 GCHandle s = GCHandle.FromIntPtr (data);
413 var self = s.Target as DeflateStreamNative;
416 return self.UnmanagedWrite (buffer, length);
419 int UnmanagedWrite (IntPtr buffer, int length)
423 if (io_buffer == null)
424 io_buffer = new byte [BufferSize];
426 int count = Math.Min (length, io_buffer.Length);
427 Marshal.Copy (buffer, io_buffer, 0, count);
428 base_stream.Write (io_buffer, 0, count);
430 buffer = new IntPtr ((byte *) buffer.ToPointer () + count);
438 static void CheckResult (int result, string where)
446 error = "Unknown error"; // Marshal.GetLastWin32() ?
448 case -2: // Z_STREAM_ERROR
449 error = "Internal error";
451 case -3: // Z_DATA_ERROR
452 error = "Corrupted data";
454 case -4: // Z_MEM_ERROR
455 error = "Not enough memory";
457 case -5: // Z_BUF_ERROR
458 error = "Internal error (no progress possible)";
460 case -6: // Z_VERSION_ERROR
461 error = "Invalid version";
464 error = "Invalid argument(s)";
470 error = "Unknown error";
474 throw new IOException (error + " " + where);
477 #if MONOTOUCH || MONODROID
478 const string LIBNAME = "__Internal";
480 const string LIBNAME = "MonoPosixHelper";
483 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
484 static extern IntPtr CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder, IntPtr data);
486 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
487 static extern int CloseZStream (IntPtr stream);
489 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
490 static extern int Flush (IntPtr stream);
492 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
493 static extern int ReadZStream (IntPtr stream, IntPtr buffer, int length);
495 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
496 static extern int WriteZStream (IntPtr stream, IntPtr buffer, int length);