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 #if MONOTOUCH || MOBILE_STATIC
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;
83 public DeflateStream (Stream stream, CompressionLevel compressionLevel)
84 : this (stream, compressionLevel, false, false)
88 public DeflateStream (Stream stream, CompressionLevel compressionLevel, bool leaveOpen)
89 : this (stream, compressionLevel, leaveOpen, false)
93 internal DeflateStream (Stream stream, CompressionLevel compressionLevel, bool leaveOpen, bool gzip)
94 : this (stream, CompressionMode.Compress, leaveOpen, gzip)
98 protected override void Dispose (bool disposing)
100 native.Dispose (disposing);
102 if (disposing && !disposed) {
106 Stream st = base_stream;
113 base.Dispose (disposing);
116 unsafe int ReadInternal (byte[] array, int offset, int count)
121 fixed (byte *b = array) {
122 IntPtr ptr = new IntPtr (b + offset);
123 return native.ReadZStream (ptr, count);
127 public override int Read (byte[] dest, int dest_offset, int count)
130 throw new ObjectDisposedException (GetType ().FullName);
132 throw new ArgumentNullException ("Destination array is null.");
134 throw new InvalidOperationException ("Stream does not support reading.");
135 int len = dest.Length;
136 if (dest_offset < 0 || count < 0)
137 throw new ArgumentException ("Dest or count is negative.");
138 if (dest_offset > len)
139 throw new ArgumentException ("destination offset is beyond array size");
140 if ((dest_offset + count) > len)
141 throw new ArgumentException ("Reading would overrun buffer");
143 return ReadInternal (dest, dest_offset, count);
146 unsafe void WriteInternal (byte[] array, int offset, int count)
151 fixed (byte *b = array) {
152 IntPtr ptr = new IntPtr (b + offset);
153 native.WriteZStream (ptr, count);
157 public override void Write (byte[] src, int src_offset, int count)
160 throw new ObjectDisposedException (GetType ().FullName);
163 throw new ArgumentNullException ("src");
166 throw new ArgumentOutOfRangeException ("src_offset");
169 throw new ArgumentOutOfRangeException ("count");
172 throw new NotSupportedException ("Stream does not support writing");
174 if (src_offset > src.Length - count)
175 throw new ArgumentException ("Buffer too small. count/offset wrong.");
177 WriteInternal (src, src_offset, count);
180 public override void Flush ()
183 throw new ObjectDisposedException (GetType ().FullName);
190 public override IAsyncResult BeginRead (byte [] buffer, int offset, int count,
191 AsyncCallback cback, object state)
194 throw new ObjectDisposedException (GetType ().FullName);
197 throw new NotSupportedException ("This stream does not support reading");
200 throw new ArgumentNullException ("buffer");
203 throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
206 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
208 if (count + offset > buffer.Length)
209 throw new ArgumentException ("Buffer too small. count/offset wrong.");
211 ReadMethod r = new ReadMethod (ReadInternal);
212 return r.BeginInvoke (buffer, offset, count, cback, state);
215 public override IAsyncResult BeginWrite (byte [] buffer, int offset, int count,
216 AsyncCallback cback, object state)
219 throw new ObjectDisposedException (GetType ().FullName);
222 throw new InvalidOperationException ("This stream does not support writing");
225 throw new ArgumentNullException ("buffer");
228 throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
231 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
233 if (count + offset > buffer.Length)
234 throw new ArgumentException ("Buffer too small. count/offset wrong.");
236 WriteMethod w = new WriteMethod (WriteInternal);
237 return w.BeginInvoke (buffer, offset, count, cback, state);
240 public override int EndRead(IAsyncResult async_result)
242 if (async_result == null)
243 throw new ArgumentNullException ("async_result");
245 AsyncResult ares = async_result as AsyncResult;
247 throw new ArgumentException ("Invalid IAsyncResult", "async_result");
249 ReadMethod r = ares.AsyncDelegate as ReadMethod;
251 throw new ArgumentException ("Invalid IAsyncResult", "async_result");
253 return r.EndInvoke (async_result);
256 public override void EndWrite (IAsyncResult async_result)
258 if (async_result == null)
259 throw new ArgumentNullException ("async_result");
261 AsyncResult ares = async_result as AsyncResult;
263 throw new ArgumentException ("Invalid IAsyncResult", "async_result");
265 WriteMethod w = ares.AsyncDelegate as WriteMethod;
267 throw new ArgumentException ("Invalid IAsyncResult", "async_result");
269 w.EndInvoke (async_result);
273 public override long Seek (long offset, SeekOrigin origin)
275 throw new NotSupportedException();
278 public override void SetLength (long value)
280 throw new NotSupportedException();
283 public Stream BaseStream {
284 get { return base_stream; }
287 public override bool CanRead {
288 get { return !disposed && mode == CompressionMode.Decompress && base_stream.CanRead; }
291 public override bool CanSeek {
292 get { return false; }
295 public override bool CanWrite {
296 get { return !disposed && mode == CompressionMode.Compress && base_stream.CanWrite; }
299 public override long Length {
300 get { throw new NotSupportedException(); }
303 public override long Position {
304 get { throw new NotSupportedException(); }
305 set { throw new NotSupportedException(); }
309 class DeflateStreamNative
311 const int BufferSize = 4096;
313 [UnmanagedFunctionPointer (CallingConvention.Cdecl)]
314 delegate int UnmanagedReadOrWrite (IntPtr buffer, int length, IntPtr data);
316 UnmanagedReadOrWrite feeder; // This will be passed to unmanaged code and used there
324 private DeflateStreamNative ()
328 public static DeflateStreamNative Create (Stream compressedStream, CompressionMode mode, bool gzip)
330 var dsn = new DeflateStreamNative ();
331 dsn.data = GCHandle.Alloc (dsn);
332 dsn.feeder = mode == CompressionMode.Compress ? new UnmanagedReadOrWrite (UnmanagedWrite) : new UnmanagedReadOrWrite (UnmanagedRead);
333 dsn.z_stream = CreateZStream (mode, gzip, dsn.feeder, GCHandle.ToIntPtr (dsn.data));
334 if (dsn.z_stream == IntPtr.Zero) {
339 dsn.base_stream = compressedStream;
343 ~DeflateStreamNative ()
348 public void Dispose (bool disposing)
350 if (disposing && !disposed) {
352 GC.SuppressFinalize (this);
356 IntPtr zz = z_stream;
357 z_stream = IntPtr.Zero;
358 if (zz != IntPtr.Zero)
359 CloseZStream (zz); // This will Flush() the remaining output if any
362 if (data.IsAllocated) {
369 var res = Flush (z_stream);
370 CheckResult (res, "Flush");
373 public int ReadZStream (IntPtr buffer, int length)
375 var res = ReadZStream (z_stream, buffer, length);
376 CheckResult (res, "ReadInternal");
380 public void WriteZStream (IntPtr buffer, int length)
382 var res = WriteZStream (z_stream, buffer, length);
383 CheckResult (res, "WriteInternal");
386 #if MONOTOUCH || MOBILE_STATIC
387 [MonoPInvokeCallback (typeof (UnmanagedReadOrWrite))]
389 static int UnmanagedRead (IntPtr buffer, int length, IntPtr data)
391 GCHandle s = GCHandle.FromIntPtr (data);
392 var self = s.Target as DeflateStreamNative;
395 return self.UnmanagedRead (buffer, length);
398 int UnmanagedRead (IntPtr buffer, int length)
400 if (io_buffer == null)
401 io_buffer = new byte [BufferSize];
403 int count = Math.Min (length, io_buffer.Length);
404 int n = base_stream.Read (io_buffer, 0, count);
406 Marshal.Copy (io_buffer, 0, buffer, n);
411 #if MONOTOUCH || MOBILE_STATIC
412 [MonoPInvokeCallback (typeof (UnmanagedReadOrWrite))]
414 static int UnmanagedWrite (IntPtr buffer, int length, IntPtr data)
416 GCHandle s = GCHandle.FromIntPtr (data);
417 var self = s.Target as DeflateStreamNative;
420 return self.UnmanagedWrite (buffer, length);
423 int UnmanagedWrite (IntPtr buffer, int length)
427 if (io_buffer == null)
428 io_buffer = new byte [BufferSize];
430 int count = Math.Min (length, io_buffer.Length);
431 Marshal.Copy (buffer, io_buffer, 0, count);
432 base_stream.Write (io_buffer, 0, count);
434 buffer = new IntPtr ((byte *) buffer.ToPointer () + count);
442 static void CheckResult (int result, string where)
450 error = "Unknown error"; // Marshal.GetLastWin32() ?
452 case -2: // Z_STREAM_ERROR
453 error = "Internal error";
455 case -3: // Z_DATA_ERROR
456 error = "Corrupted data";
458 case -4: // Z_MEM_ERROR
459 error = "Not enough memory";
461 case -5: // Z_BUF_ERROR
462 error = "Internal error (no progress possible)";
464 case -6: // Z_VERSION_ERROR
465 error = "Invalid version";
468 error = "Invalid argument(s)";
474 error = "Unknown error";
478 throw new IOException (error + " " + where);
481 #if MONOTOUCH || MONODROID
482 const string LIBNAME = "__Internal";
484 const string LIBNAME = "MonoPosixHelper";
487 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
488 static extern IntPtr CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder, IntPtr data);
490 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
491 static extern int CloseZStream (IntPtr stream);
493 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
494 static extern int Flush (IntPtr stream);
496 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
497 static extern int ReadZStream (IntPtr stream, IntPtr buffer, int length);
499 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
500 static extern int WriteZStream (IntPtr stream, IntPtr buffer, int length);