8249d786c2e1a5d68f72e0981878d3c0aec30e80
[mono.git] / mcs / class / System / System.IO.Compression / DeflateStream.cs
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 <clahey@ximian.com>
7 //      Gonzalo Paniagua Javier (gonzalo@novell.com)
8 //  Marek Safar (marek.safar@gmail.com)
9 //
10 // (c) Copyright 2004,2009 Novell, Inc. <http://www.novell.com>
11 // Copyright (C) 2013 Xamarin Inc (http://www.xamarin.com)
12 //
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:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
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.
31 //
32
33 using System;
34 using System.IO;
35 using System.Runtime.InteropServices;
36 using System.Runtime.Remoting.Messaging;
37
38 namespace System.IO.Compression
39 {
40         public class DeflateStream : Stream
41         {
42                 delegate int ReadMethod (byte[] array, int offset, int count);
43                 delegate void WriteMethod (byte[] array, int offset, int count);
44
45                 Stream base_stream;
46                 CompressionMode mode;
47                 bool leaveOpen;
48                 bool disposed;
49                 DeflateStreamNative native;
50
51                 public DeflateStream (Stream stream, CompressionMode mode) :
52                         this (stream, mode, false, false)
53                 {
54                 }
55
56                 public DeflateStream (Stream stream, CompressionMode mode, bool leaveOpen) :
57                         this (stream, mode, leaveOpen, false)
58                 {
59                 }
60
61                 internal DeflateStream (Stream stream, CompressionMode mode, bool leaveOpen, int windowsBits) :
62                         this (stream, mode, leaveOpen, true)
63                 {
64                 }
65
66                 internal DeflateStream (Stream compressedStream, CompressionMode mode, bool leaveOpen, bool gzip)
67                 {
68                         if (compressedStream == null)
69                                 throw new ArgumentNullException ("compressedStream");
70
71                         if (mode != CompressionMode.Compress && mode != CompressionMode.Decompress)
72                                 throw new ArgumentException ("mode");
73
74                         this.base_stream = compressedStream;
75
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.");
79                         }
80                         this.mode = mode;
81                         this.leaveOpen = leaveOpen;
82                 }
83                 
84                 public DeflateStream (Stream stream, CompressionLevel compressionLevel)
85                         : this (stream, compressionLevel, false, false)
86                 {
87                 }
88                 
89                 public DeflateStream (Stream stream, CompressionLevel compressionLevel, bool leaveOpen)
90                         : this (stream, compressionLevel, leaveOpen, false)
91                 {
92                 }
93
94                 internal DeflateStream (Stream stream, CompressionLevel compressionLevel, bool leaveOpen, int windowsBits)
95                         : this (stream, compressionLevel, leaveOpen, true)
96                 {
97                 }
98
99                 internal DeflateStream (Stream stream, CompressionLevel compressionLevel, bool leaveOpen, bool gzip)
100                         : this (stream, CompressionMode.Compress, leaveOpen, gzip)
101                 {
102                 }               
103
104                 protected override void Dispose (bool disposing)
105                 {
106                         native.Dispose (disposing);
107
108                         if (disposing && !disposed) {
109                                 disposed = true;
110
111                                 if (!leaveOpen) {
112                                         Stream st = base_stream;
113                                         if (st != null)
114                                                 st.Close ();
115                                         base_stream = null;
116                                 }
117                         }
118
119                         base.Dispose (disposing);
120                 }
121
122                 unsafe int ReadInternal (byte[] array, int offset, int count)
123                 {
124                         if (count == 0)
125                                 return 0;
126
127                         fixed (byte *b = array) {
128                                 IntPtr ptr = new IntPtr (b + offset);
129                                 return native.ReadZStream (ptr, count);
130                         }
131                 }
132
133                 public override int Read (byte[] array, int offset, int count)
134                 {
135                         if (disposed)
136                                 throw new ObjectDisposedException (GetType ().FullName);
137                         if (array == null)
138                                 throw new ArgumentNullException ("Destination array is null.");
139                         if (!CanRead)
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.");
144                         if (offset > len)
145                                 throw new ArgumentException ("destination offset is beyond array size");
146                         if ((offset + count) > len)
147                                 throw new ArgumentException ("Reading would overrun buffer");
148
149                         return ReadInternal (array, offset, count);
150                 }
151
152                 unsafe void WriteInternal (byte[] array, int offset, int count)
153                 {
154                         if (count == 0)
155                                 return;
156
157                         fixed (byte *b = array) {
158                                 IntPtr ptr = new IntPtr (b + offset);
159                                 native.WriteZStream (ptr, count);
160                         }
161                 }
162
163                 public override void Write (byte[] array, int offset, int count)
164                 {
165                         if (disposed)
166                                 throw new ObjectDisposedException (GetType ().FullName);
167
168                         if (array == null)
169                                 throw new ArgumentNullException ("array");
170
171                         if (offset < 0)
172                                 throw new ArgumentOutOfRangeException ("offset");
173
174                         if (count < 0)
175                                 throw new ArgumentOutOfRangeException ("count");
176
177                         if (!CanWrite)
178                                 throw new NotSupportedException ("Stream does not support writing");
179
180                         if (offset > array.Length - count)
181                                 throw new ArgumentException ("Buffer too small. count/offset wrong.");
182
183                         WriteInternal (array, offset, count);
184                 }
185
186                 public override void Flush ()
187                 {
188                         if (disposed)
189                                 throw new ObjectDisposedException (GetType ().FullName);
190
191                         if (CanWrite) {
192                                 native.Flush ();
193                         }
194                 }
195
196                 public override IAsyncResult BeginRead (byte [] array, int offset, int count,
197                                                         AsyncCallback asyncCallback, object asyncState)
198                 {
199                         if (disposed)
200                                 throw new ObjectDisposedException (GetType ().FullName);
201
202                         if (!CanRead)
203                                 throw new NotSupportedException ("This stream does not support reading");
204
205                         if (array == null)
206                                 throw new ArgumentNullException ("array");
207
208                         if (count < 0)
209                                 throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
210
211                         if (offset < 0)
212                                 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
213
214                         if (count + offset > array.Length)
215                                 throw new ArgumentException ("Buffer too small. count/offset wrong.");
216
217                         ReadMethod r = new ReadMethod (ReadInternal);
218                         return r.BeginInvoke (array, offset, count, asyncCallback, asyncState);
219                 }
220
221                 public override IAsyncResult BeginWrite (byte [] array, int offset, int count,
222                                                         AsyncCallback asyncCallback, object asyncState)
223                 {
224                         if (disposed)
225                                 throw new ObjectDisposedException (GetType ().FullName);
226
227                         if (!CanWrite)
228                                 throw new InvalidOperationException ("This stream does not support writing");
229
230                         if (array == null)
231                                 throw new ArgumentNullException ("array");
232
233                         if (count < 0)
234                                 throw new ArgumentOutOfRangeException ("count", "Must be >= 0");
235
236                         if (offset < 0)
237                                 throw new ArgumentOutOfRangeException ("offset", "Must be >= 0");
238
239                         if (count + offset > array.Length)
240                                 throw new ArgumentException ("Buffer too small. count/offset wrong.");
241
242                         WriteMethod w = new WriteMethod (WriteInternal);
243                         return w.BeginInvoke (array, offset, count, asyncCallback, asyncState);                 
244                 }
245
246                 public override int EndRead(IAsyncResult asyncResult)
247                 {
248                         if (asyncResult == null)
249                                 throw new ArgumentNullException ("asyncResult");
250
251                         AsyncResult ares = asyncResult as AsyncResult;
252                         if (ares == null)
253                                 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
254
255                         ReadMethod r = ares.AsyncDelegate as ReadMethod;
256                         if (r == null)
257                                 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
258
259                         return r.EndInvoke (asyncResult);
260                 }
261
262                 public override void EndWrite (IAsyncResult asyncResult)
263                 {
264                         if (asyncResult == null)
265                                 throw new ArgumentNullException ("asyncResult");
266
267                         AsyncResult ares = asyncResult as AsyncResult;
268                         if (ares == null)
269                                 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
270
271                         WriteMethod w = ares.AsyncDelegate as WriteMethod;
272                         if (w == null)
273                                 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
274
275                         w.EndInvoke (asyncResult);
276                         return;
277                 }
278
279                 public override long Seek (long offset, SeekOrigin origin)
280                 {
281                         throw new NotSupportedException();
282                 }
283
284                 public override void SetLength (long value)
285                 {
286                         throw new NotSupportedException();
287                 }
288
289                 public Stream BaseStream {
290                         get { return base_stream; }
291                 }
292
293                 public override bool CanRead {
294                         get { return !disposed && mode == CompressionMode.Decompress && base_stream.CanRead; }
295                 }
296
297                 public override bool CanSeek {
298                         get { return false; }
299                 }
300
301                 public override bool CanWrite {
302                         get { return !disposed && mode == CompressionMode.Compress && base_stream.CanWrite; }
303                 }
304
305                 public override long Length {
306                         get { throw new NotSupportedException(); }
307                 }
308
309                 public override long Position {
310                         get { throw new NotSupportedException(); }
311                         set { throw new NotSupportedException(); }
312                 }
313         }
314
315         class DeflateStreamNative
316         {
317                 const int BufferSize = 4096;
318
319                 [UnmanagedFunctionPointer (CallingConvention.Cdecl)]
320                 delegate int UnmanagedReadOrWrite (IntPtr buffer, int length, IntPtr data);
321
322                 UnmanagedReadOrWrite feeder; // This will be passed to unmanaged code and used there
323
324                 Stream base_stream;
325                 IntPtr z_stream;
326                 GCHandle data;
327                 bool disposed;
328                 byte [] io_buffer;
329
330                 private DeflateStreamNative ()
331                 {
332                 }
333
334                 public static DeflateStreamNative Create (Stream compressedStream, CompressionMode mode, bool gzip)
335                 {
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) {
341                                 dsn.Dispose (true);
342                                 return null;
343                         }
344
345                         dsn.base_stream = compressedStream;
346                         return dsn;
347                 }
348
349                 ~DeflateStreamNative ()
350                 {
351                         Dispose (false);
352                 }
353
354                 public void Dispose (bool disposing)
355                 {
356                         if (disposing && !disposed) {
357                                 disposed = true;
358                                 GC.SuppressFinalize (this);
359                         
360                                 io_buffer = null;
361                         
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
366                         }
367
368                         if (data.IsAllocated) {
369                                 data.Free ();
370                         }
371                 }
372
373                 public void Flush ()
374                 {
375                         var res = Flush (z_stream);
376                         CheckResult (res, "Flush");
377                 }
378
379                 public int ReadZStream (IntPtr buffer, int length)
380                 {
381                         var res = ReadZStream (z_stream, buffer, length);
382                         CheckResult (res, "ReadInternal");
383                         return res;
384                 }
385
386                 public void WriteZStream (IntPtr buffer, int length)
387                 {
388                         var res = WriteZStream (z_stream, buffer, length);
389                         CheckResult (res, "WriteInternal");
390                 }
391
392                 [Mono.Util.MonoPInvokeCallback (typeof (UnmanagedReadOrWrite))]
393                 static int UnmanagedRead (IntPtr buffer, int length, IntPtr data)
394                 {
395                         GCHandle s = GCHandle.FromIntPtr (data);
396                         var self = s.Target as DeflateStreamNative;
397                         if (self == null)
398                                 return -1;
399                         return self.UnmanagedRead (buffer, length);
400                 }
401
402                 int UnmanagedRead (IntPtr buffer, int length)
403                 {
404                         if (io_buffer == null)
405                                 io_buffer = new byte [BufferSize];
406
407                         int count = Math.Min (length, io_buffer.Length);
408                         int n = base_stream.Read (io_buffer, 0, count);
409                         if (n > 0)
410                                 Marshal.Copy (io_buffer, 0, buffer, n);
411
412                         return n;
413                 }
414
415                 [Mono.Util.MonoPInvokeCallback (typeof (UnmanagedReadOrWrite))]
416                 static int UnmanagedWrite (IntPtr buffer, int length, IntPtr data)
417                 {
418                         GCHandle s = GCHandle.FromIntPtr (data);
419                         var self = s.Target as DeflateStreamNative;
420                         if (self == null)
421                                 return -1;
422                         return self.UnmanagedWrite (buffer, length);
423                 }
424
425                 int UnmanagedWrite (IntPtr buffer, int length)
426                 {
427                         int total = 0;
428                         while (length > 0) {
429                                 if (io_buffer == null)
430                                         io_buffer = new byte [BufferSize];
431
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);
435                                 unsafe {
436                                         buffer = new IntPtr ((byte *) buffer.ToPointer () + count);
437                                 }
438                                 length -= count;
439                                 total += count;
440                         }
441                         return total;
442                 }
443
444                 static void CheckResult (int result, string where)
445                 {
446                         if (result >= 0)
447                                 return;
448
449                         string error;
450                         switch (result) {
451                         case -1: // Z_ERRNO
452                                 error = "Unknown error"; // Marshal.GetLastWin32() ?
453                                 break;
454                         case -2: // Z_STREAM_ERROR
455                                 error = "Internal error";
456                                 break;
457                         case -3: // Z_DATA_ERROR
458                                 error = "Corrupted data";
459                                 break;
460                         case -4: // Z_MEM_ERROR
461                                 error = "Not enough memory";
462                                 break;
463                         case -5: // Z_BUF_ERROR
464                                 error = "Internal error (no progress possible)";
465                                 break;
466                         case -6: // Z_VERSION_ERROR
467                                 error = "Invalid version";
468                                 break;
469                         case -10:
470                                 error = "Invalid argument(s)";
471                                 break;
472                         case -11:
473                                 error = "IO error";
474                                 break;
475                         default:
476                                 error = "Unknown error";
477                                 break;
478                         }
479
480                         throw new IOException (error + " " + where);
481                 }
482
483 #if MONOTOUCH || MONODROID
484                 const string LIBNAME = "__Internal";
485 #else
486                 const string LIBNAME = "MonoPosixHelper";
487 #endif
488
489 #if !ORBIS
490                 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
491                 static extern IntPtr CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder, IntPtr data);
492
493                 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
494                 static extern int CloseZStream (IntPtr stream);
495
496                 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
497                 static extern int Flush (IntPtr stream);
498
499                 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
500                 static extern int ReadZStream (IntPtr stream, IntPtr buffer, int length);
501
502                 [DllImport (LIBNAME, CallingConvention=CallingConvention.Cdecl)]
503                 static extern int WriteZStream (IntPtr stream, IntPtr buffer, int length);
504 #else
505                 static IntPtr CreateZStream (CompressionMode compress, bool gzip, UnmanagedReadOrWrite feeder, IntPtr data)
506                 {
507                         throw new PlatformNotSupportedException ();
508                 }
509
510                 static int CloseZStream (IntPtr stream)
511                 {
512                         throw new PlatformNotSupportedException ();
513                 }
514
515                 static int Flush (IntPtr stream)
516                 {
517                         throw new PlatformNotSupportedException ();
518                 }
519
520                 static int ReadZStream (IntPtr stream, IntPtr buffer, int length)
521                 {
522                         throw new PlatformNotSupportedException ();
523                 }
524
525                 static int WriteZStream (IntPtr stream, IntPtr buffer, int length)
526                 {
527                         throw new PlatformNotSupportedException ();
528                 }
529 #endif
530
531         }
532 }
533