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;
42 namespace System.IO.Compression
44 public class DeflateStream : Stream
46 delegate int ReadMethod (byte[] array, int offset, int count);
47 delegate void WriteMethod (byte[] array, int offset, int count);
53 DeflateStreamNative native;
55 public DeflateStream (Stream compressedStream, CompressionMode mode) :
56 this (compressedStream, mode, false, false)
60 public DeflateStream (Stream compressedStream, CompressionMode mode, bool leaveOpen) :
61 this (compressedStream, mode, leaveOpen, false)
65 internal DeflateStream (Stream compressedStream, CompressionMode mode, bool leaveOpen, bool gzip)
67 if (compressedStream == null)
68 throw new ArgumentNullException ("compressedStream");
70 if (mode != CompressionMode.Compress && mode != CompressionMode.Decompress)
71 throw new ArgumentException ("mode");
73 this.base_stream = compressedStream;
75 this.native = DeflateStreamNative.Create (compressedStream, mode, gzip);
76 if (this.native == null) {
77 throw new NotImplementedException ("Failed to initialize zlib. You probably have an old zlib installed. Version 1.2.0.4 or later is required.");
80 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, bool gzip)
95 : this (stream, CompressionMode.Compress, leaveOpen, gzip)
100 protected override void Dispose (bool disposing)
102 native.Dispose (disposing);
104 if (disposing && !disposed) {
108 Stream st = base_stream;
115 base.Dispose (disposing);
118 unsafe int ReadInternal (byte[] array, int offset, int count)
123 fixed (byte *b = array) {
124 IntPtr ptr = new IntPtr (b + offset);
125 return native.ReadZStream (ptr, count);
129 public override int Read (byte[] dest, int dest_offset, int count)
132 throw new ObjectDisposedException (GetType ().FullName);
134 throw new ArgumentNullException ("Destination array is null.");
136 throw new InvalidOperationException ("Stream does not support reading.");
137 int len = dest.Length;
138 if (dest_offset < 0 || count < 0)
139 throw new ArgumentException ("Dest or count is negative.");
140 if (dest_offset > len)
141 throw new ArgumentException ("destination offset is beyond array size");
142 if ((dest_offset + count) > len)
143 throw new ArgumentException ("Reading would overrun buffer");
145 return ReadInternal (dest, dest_offset, count);
148 unsafe void WriteInternal (byte[] array, int offset, int count)
153 fixed (byte *b = array) {
154 IntPtr ptr = new IntPtr (b + offset);
155 native.WriteZStream (ptr, count);
159 public override void Write (byte[] src, int src_offset, int count)
162 throw new ObjectDisposedException (GetType ().FullName);
165 throw new ArgumentNullException ("src");
168 throw new ArgumentOutOfRangeException ("src_offset");
171 throw new ArgumentOutOfRangeException ("count");
174 throw new NotSupportedException ("Stream does not support writing");
176 WriteInternal (src, src_offset, count);
179 public override void Flush ()
182 throw new ObjectDisposedException (GetType ().FullName);
189 public override IAsyncResult BeginRead (byte [] buffer, int offset, int count,
190 AsyncCallback cback, object state)
193 throw new ObjectDisposedException (GetType ().FullName);
196 throw new NotSupportedException ("This stream does not support reading");
199 throw new ArgumentNullException ("buffer");
202 throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
205 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
207 if (count + offset > buffer.Length)
208 throw new ArgumentException ("Buffer too small. count/offset wrong.");
210 ReadMethod r = new ReadMethod (ReadInternal);
211 return r.BeginInvoke (buffer, offset, count, cback, state);
214 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int count,
215 AsyncCallback cback, object state)
218 throw new ObjectDisposedException (GetType ().FullName);
221 throw new InvalidOperationException ("This stream does not support writing");
224 throw new ArgumentNullException ("buffer");
227 throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
230 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
232 if (count + offset > buffer.Length)
233 throw new ArgumentException ("Buffer too small. count/offset wrong.");
235 WriteMethod w = new WriteMethod (WriteInternal);
236 return w.BeginInvoke (buffer, offset, count, cback, state);
239 public override int EndRead(IAsyncResult async_result)
241 if (async_result == null)
242 throw new ArgumentNullException ("async_result");
244 AsyncResult ares = async_result as AsyncResult;
246 throw new ArgumentException ("Invalid IAsyncResult", "async_result");
248 ReadMethod r = ares.AsyncDelegate as ReadMethod;
250 throw new ArgumentException ("Invalid IAsyncResult", "async_result");
252 return r.EndInvoke (async_result);
255 public override void EndWrite (IAsyncResult async_result)
257 if (async_result == null)
258 throw new ArgumentNullException ("async_result");
260 AsyncResult ares = async_result as AsyncResult;
262 throw new ArgumentException ("Invalid IAsyncResult", "async_result");
264 WriteMethod w = ares.AsyncDelegate as WriteMethod;
266 throw new ArgumentException ("Invalid IAsyncResult", "async_result");
268 w.EndInvoke (async_result);
272 public override long Seek (long offset, SeekOrigin origin)
274 throw new NotSupportedException();
277 public override void SetLength (long value)
279 throw new NotSupportedException();
282 public Stream BaseStream {
283 get { return base_stream; }
286 public override bool CanRead {
287 get { return !disposed && mode == CompressionMode.Decompress && base_stream.CanRead; }
290 public override bool CanSeek {
291 get { return false; }
294 public override bool CanWrite {
295 get { return !disposed && mode == CompressionMode.Compress && base_stream.CanWrite; }
298 public override long Length {
299 get { throw new NotSupportedException(); }
302 public override long Position {
303 get { throw new NotSupportedException(); }
304 set { throw new NotSupportedException(); }
308 class DeflateStreamNative
310 const int BufferSize = 4096;
312 [UnmanagedFunctionPointer (CallingConvention.Cdecl)]
313 delegate int UnmanagedReadOrWrite (IntPtr buffer, int length, IntPtr data);
315 UnmanagedReadOrWrite feeder; // This will be passed to unmanaged code and used there
323 private DeflateStreamNative ()
327 public static DeflateStreamNative Create (Stream compressedStream, CompressionMode mode, bool gzip)
329 var dsn = new DeflateStreamNative ();
330 dsn.data = GCHandle.Alloc (dsn);
331 dsn.feeder = mode == CompressionMode.Compress ? new UnmanagedReadOrWrite (UnmanagedWrite) : new UnmanagedReadOrWrite (UnmanagedRead);
332 dsn.z_stream = CreateZStream (mode, gzip, dsn.feeder, GCHandle.ToIntPtr (dsn.data));
333 if (dsn.z_stream == IntPtr.Zero) {
338 dsn.base_stream = compressedStream;
342 ~DeflateStreamNative ()
347 public void Dispose (bool disposing)
349 if (disposing && !disposed) {
351 GC.SuppressFinalize (this);
355 IntPtr zz = z_stream;
356 z_stream = IntPtr.Zero;
357 if (zz != IntPtr.Zero)
358 CloseZStream (zz); // This will Flush() the remaining output if any
361 if (data.IsAllocated) {
368 var res = Flush (z_stream);
369 CheckResult (res, "Flush");
372 public int ReadZStream (IntPtr buffer, int length)
374 var res = ReadZStream (z_stream, buffer, length);
375 CheckResult (res, "ReadInternal");
379 public void WriteZStream (IntPtr buffer, int length)
381 var res = WriteZStream (z_stream, buffer, length);
382 CheckResult (res, "WriteInternal");
386 [MonoPInvokeCallback (typeof (UnmanagedReadOrWrite))]
388 static int UnmanagedRead (IntPtr buffer, int length, IntPtr data)
390 GCHandle s = GCHandle.FromIntPtr (data);
391 var self = s.Target as DeflateStreamNative;
394 return self.UnmanagedRead (buffer, length);
397 int UnmanagedRead (IntPtr buffer, int length)
399 if (io_buffer == null)
400 io_buffer = new byte [BufferSize];
402 int count = Math.Min (length, io_buffer.Length);
403 int n = base_stream.Read (io_buffer, 0, count);
405 Marshal.Copy (io_buffer, 0, buffer, n);
411 [MonoPInvokeCallback (typeof (UnmanagedReadOrWrite))]
413 static int UnmanagedWrite (IntPtr buffer, int length, IntPtr data)
415 GCHandle s = GCHandle.FromIntPtr (data);
416 var self = s.Target as DeflateStreamNative;
419 return self.UnmanagedWrite (buffer, length);
422 int UnmanagedWrite (IntPtr buffer, int length)
426 if (io_buffer == null)
427 io_buffer = new byte [BufferSize];
429 int count = Math.Min (length, io_buffer.Length);
430 Marshal.Copy (buffer, io_buffer, 0, count);
431 base_stream.Write (io_buffer, 0, count);
433 buffer = new IntPtr ((byte *) buffer.ToPointer () + count);
441 static void CheckResult (int result, string where)
449 error = "Unknown error"; // Marshal.GetLastWin32() ?
451 case -2: // Z_STREAM_ERROR
452 error = "Internal error";
454 case -3: // Z_DATA_ERROR
455 error = "Corrupted data";
457 case -4: // Z_MEM_ERROR
458 error = "Not enough memory";
460 case -5: // Z_BUF_ERROR
461 error = "Internal error (no progress possible)";
463 case -6: // Z_VERSION_ERROR
464 error = "Invalid version";
467 error = "Invalid argument(s)";
473 error = "Unknown error";
477 throw new IOException (error + " " + where);
480 #if MONOTOUCH || MONODROID
481 const string LIBNAME = "__Internal";
483 const string LIBNAME = "MonoPosixHelper";
486 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
487 static extern IntPtr CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder, IntPtr data);
489 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
490 static extern int CloseZStream (IntPtr stream);
492 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
493 static extern int Flush (IntPtr stream);
495 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
496 static extern int ReadZStream (IntPtr stream, IntPtr buffer, int length);
498 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
499 static extern int WriteZStream (IntPtr stream, IntPtr buffer, int length);